所以我有一个2D数组,它应该向右旋转90度,但它向左旋转。真的无法找出原因
公共类CrackCode16 {
public static void main (String args[]){
int [] [] oldarray = new int [3][3];
int value = 1;
for (int i = 0; i < 3; i++){
for (int j =0; j<3; j++){
oldarray[i][j] = value;
value++;
}
}
for (int i = 0; i < 3; i++){
for (int j =0; j<3; j++){
System.out.print(oldarray[i][j] + "\t");
}
System.out.println("");
}
oldarray = rotate(oldarray, 3);
System.out.println("");
for (int i = 0; i < 3; i++){
for (int j =0; j<3; j++){
System.out.print(oldarray[i][j] + "\t");
}
System.out.println("");
}
}
public static int [][] rotate (int [][] passedIn, int n){
int [][] newarray = new int [n][n];
for (int i = 0; i < n; i++){
for (int j =0; j<n; j++){
newarray[i][j] = passedIn [j][n-1-i];
}
}
return newarray;
}
}
输出:
1 2 3
4 5 6
7 8 9
3 6 9
2 5 8
1 4 7
答案 0 :(得分:1)
newArray[i][j] = passedIn [n-1-j][i];
而不是
newarray[i][j] = passedIn [j][n-1-i];
此外,在使用Java8时,您可以考虑使用Stream
来打印数组:
Stream.of(oldarray).forEach(e -> System.out.println(Arrays.toString(e)));