2017-05-06 103 views
-1

我有一個二維數組,我的目標是找到所有數字的總和和所有數字的對角線的總和。二維輸入只允許第一行

BufferedReader kb = new BufferedReader(new InputStreamReader(System.in)); 
int [][] a=new int [5][5]; 
int same=0; 
int sum=0; 
System.out.println("Please enter your numbers"); 
for(int r=0;r<5;r++) 
for(int c=0;r<5;r++) 
a[r][c]=Integer.parseInt(kb.readLine()); 
for(int r=0;r<5;r++) 
for(int c=0;r<5;r++) 
sum=sum+a[r][c]; 
for(int r=0;r<5;r++) 
for(int c=0;r<5;r++) 
if (r==c) 
{same=same+a[r][c];} 

System.out.println("The sum of the diaganols is "+same+" The sum of everything is "+sum); 

我已經打開一個雙維陣列,但是當我啓動程序我只能輸入5號,其對應於第一行。

我真的很新的編程,請原諒我任何愚蠢的錯誤,我meake,謝謝!

回答

0

那是因爲你在for循環中使用相同的變量來獲取輸入。

for(int r=0;r<5;r++) 
//for r = 0 
for(int c=0;r<5;r++) 
//r 0 to 5 (take 5 input) 

這裏,r在內部循環達到5所以無論是循環退出作爲退出條件是相同的兩種(R < 5)。你應該像下面這樣做 - :

for (int i = 0; i < 5 ; i++){ 
for (int j = 0; j < 5 ; j++){ 
    a[i][j] = //read input 
} 
}