2015-04-20 92 views
0

查找行的最大值的第一個數組可以正常工作,但由於某些原因,列總和的數組列出的內容完全不在列數組之和的元素。如何從二維數組的列總和中找到數組的最大值

import java.util.*; 

public class Quiz 
{ 
    public static void main(String[] args) 
    { 
     Scanner input = new Scanner(System.in); 
     Scanner input2 = new Scanner(System.in); 

     System.out.println("Please eneter 20 numbers"); 

     int userinput[][] = new int[4][5]; 

     String StringInput; 

     for(int column = 0; column < 4; column++) 
     { 
      for(int row = 0; row < 5; row++) 
      { 
       userinput[column][row] = input.nextInt(); 
      } 
     } 

     for(int column = 0; column < 4; column++) 
     { 
      for(int row = 0; row < 5; row++) 
      { 
       System.out.print(userinput[column][row] + " "); 
      } 
      System.out.println(); 
     } 


     int[] sumOfRows = new int[userinput.length]; 

     int sumR = 0; 

     int largetstrow = sumOfRows[0]; 

     for(int row = 0; row < userinput.length; row++) 
     { 
      for(int col = 0; col < userinput[0].length; col++) 
      { 
       sumR += userinput[row][col]; 
      } 
      sumOfRows[row] = sumR; 
      sumR = 0; 

      if(sumOfRows[row] > largetstrow) 
       largetstrow = sumOfRows[row]; 
     } 
     System.out.println("The sum of each rows are " + Arrays.toString(sumOfRows)); 
     System.out.println(largetstrow); 


     int size = userinput[0].length; 
     int sumOfColumn[] = new int[size]; // used for columns addition 

     int largestColumn = sumOfColumn[0]; 

     int highestSumC = 0; 
     int highestIndexC = 0; 
     for (int i = 0; i < userinput.length; i++) 
     { 
      for (int j = 0; j < userinput[i].length; j++) 
      { 
       sumOfColumn[j] += userinput[i][j]; 
       if(sumOfColumn[i] > highestSumC) 
       { 
        highestSumC = sumOfColumn[i]; 
        highestIndexC = i; 
       } 
      } 
     } 

     System.out.println("The sum of each columns are " + Arrays.toString(sumOfColumn)); 


     System.out.println(highestSumC); 
    } 
} 

回答

0
 // it's j 
     sumOfColumn[j] += userinput[i][j]; 

     // it's i 
     if(sumOfColumn[i] > highestSumC) 
     { 
      highestSumC = sumOfColumn[i]; 
      highestIndexC = i; 
     } 

爲什麼從j切換到我?

如果您顛倒循環並將列循環作爲外部循環和行作爲內部循環,那麼這可能會更容易,那麼您幾乎可以以與第一個循環相同的方式進行操作,而不必中間數組保持運行總數。

此外,溝ij作爲變量名支持rowcol以幫助您計算出發生了什麼。

相關問題