0
我想解決使用Java的多維數組上的問題。我需要打印所有對角線顯示給定二維矩陣的數字。我也做了一個方案,但不能對其餘元件做完成解決方案所需的輸入
public class TwoDimensionalArray {
private static int[][] array = {{1,2,3,4},{5,6,7,8},{9,10,11,12,}, {13,14,15,16}};
public static void main(String args[]){
for (int i=0;i<4; i++){
for(int j=0;j < 4; j++){
System.out.print(" "+ array[i][j] +" ");
}
System.out.println();
}
System.out.println();
for (int i = 0;i < 4; i++){
int offset = 0;
for(int j = offset;j <= i; j++){
System.out.print("i >> "+i+" ");
System.out.print("j >> "+j);
System.out.println(" == "+ array[i][i+offset] +" ");
}
offset++;
}
}
}
我開始寫下面的代碼以獲得正確打印第一對角線元素。
for (int i = 0;i < 4; i++){
int offset = 0;
System.out.print(array[i][i+offset] +" ");
offset++;
}
輸出:1 6 11 16
但是當我嘗試通過增加內部的循環擴展同樣的方法,我開始每天導致它打印元素超過一次,而不是一次迭代從0
直到i
具有正確的輸出。我的方法是正確的,或者我在執行inner for循環時缺少一些東西。
所需的輸出應是象下面這樣:
1 6 11 16
2 7 12
3 8
4
5 10 15
6 11 16
7 12
8
9 14
10 15
11 16
12
這不是一個分配。我只是想提高我的編程技能。也請讓我知道這個問題的難度級別爲1到5,5是最難的,1是簡單的。
我得到了我要去哪裏錯了。 – zilcuanu