所以我應該創建一個用於創建一個3×4陣列看起來像一個程序:二維數組:創建,初始化和總結
1 2 3 4
1 2 3 4
1 2 3 4
我設法想出一個辦法來打印陣列,但我的指示的第二部分告訴我總結我的總數。當我編譯並運行這個程序時,我得到結果42,它應該是30.我的方向也告訴我,我需要使用嵌套for循環來創建和初始化AND以便總結數組。
public class PartA {
public static void main (String[] args){
int [][] array = new int [3][4];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
int k = array[0][j];
int l = array[1][j];
array[0][j] = (i+1)+(j);
array[1][j] = k;
array[2][j] = l;
System.out.print(array[i][j] + " ");
}
System.out.println();
}
int sum = 0;
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
sum += array[i][j];
}
}
System.out.println("The sum of the contents of this array is " + sum);
}
}
我忘了這樣一個問題:我假設我做錯了什麼與初始化數組。總結數組的代碼是我老師給我使用的。那麼我在初始化數組時做了什麼錯誤?它是否與int k,l有關? –
您是否認爲您現在正在修改相同陣列的值並在某個時間點進行打印? – SMA