2016-12-06 34 views
1

爲什麼我會在minRow和minRowIndex上得到0?謝謝誰回覆。我嘗試在二維數組中找到總和最小的行,但我只得到0

import java.util.Scanner; 

public class test1 { 

public static void main(String[] arg) { 

    Scanner in = new Scanner(System.in); 

    int [][] matrix = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}}; 

    int minRow = 0; 
    int minRowAvg = 0; 
    int minRowIndex = 0; 

    for (int row = 1; row < matrix.length; row++){ 
     int rowSum = 0; 
     for (int col = 0; col < matrix[row].length; col++){ 
      rowSum += matrix[row][col]; 
     } 

     if (rowSum < minRow && rowSum > 0){ 
      minRow = rowSum; 
      minRowIndex = row; 
     } 
    } 
    System.out.println("Row " + minRowIndex + " has the minimum sum of " + minRow); 

    } 

} 
+0

您的代碼需要更多格式 – Dbz

回答

2

rowSum絕不會小了minRow,因爲你初始化minRow爲0

你應該把它初始化爲Integer.MAX_VALUE

int minRow = Integer.MAX_VALUE; 
+0

謝謝!我沒有想到 – Neo

+0

@Neo不客氣! – Eran

0

首先,在你的第一個循環中,排在變量1開始,所以你永遠不會檢查你的第一個矩陣行,它應該爲0。

你minRow初始化從0開始,只有已修改您的

if (rowSum < minRow && rowSum > 0){ 
     minRow = rowSum; 
     minRowIndex = row; 
} 

您的情況始終是錯誤的,因爲rowSum總是優於minRow。這與你的minRowIndex相同。

相關問題