我正在尝试反转从 .txt 文件导入的 double 组。然而,当我运行我的程序时,它只反转数组的前半部分,而数组的另一半打印出 0。有什么建议么?这是我的代码:
package arrayreverse;
import java.util.Scanner;
import java.io.*;
public class ArrayReverse {
public static void main(String[] args) throws IOException {
try{
File abc = new File ("filelocation");
Scanner reader = new Scanner(abc);
int [][] a = new int[5][10];
int [][] b = new int [5][10];
for (int row = a.length - 1; row >= 0; row--){
for (int col = a[row].length - 1; col >= 0; col--){
a[row][col] = reader.nextInt();
b[row][col] = a[row][col];
a[row][col] = b[4-row][9-col];
System.out.print(a[row][col]+" ");
}
System.out.println();
}
}
catch (IOException i){
}
}
}
最佳答案
a[row][col] = reader.nextInt();
b[row][col] = a[row][col];
a[row][col] = b[4-row][9-col]; //problem is here
//until u reach half way b's elements have no
//values assigned yet (0 by default)
尝试以下操作:
a[row][col] = reader.nextInt();
b[a.length - 1 - row][a[row].length - 1 - col] = a[row][col];
a
和 b
应该在循环完成后相互反转。
关于java - 在反转二维数组时遇到问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8455106/