从java中的.txt文件中读取2D数组



data.txt中有一个问题,我们有4行3列,这给了我超出范围的错误。请有人解决这个问题,但当我在行和列中通过4x4时,它运行良好,但不符合项目要求

public class ReadMagicSquare {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here

Scanner sc = new Scanner(new BufferedReader(new FileReader("data.txt")));
int rows = 4;
int columns = 3;
int [][] myArray = new int[rows][columns];
while(sc.hasNextLine()) {
for (int i=0; i<myArray.length; i++) {
String[] line = sc.nextLine().trim().split(" ");
for (int j=0; j<line.length; j++) {
myArray[i][j] = Integer.parseInt(line[j]);
}
}
}

for(int i=0;i<myArray.length;i++){
for(int j=0;j<myArray.length;j++){
System.out.print(myArray[i][j]+" ");
}
System.out.println();
}

}

}

在data.txt文件中

2 -1 1
6 4 24
2 19 7
for(int i=0;i<myArray.length;i++){
for(int j=0;j<myArray.length;j++){
System.out.print(myArray[i][j]+" ");
}
System.out.println();
}

myArray.length给出了2D数组中的行数,因此在内部循环中,j将从0 to less than 4而不是0 to less than 3,这将给您一个越界错误。

您需要将j从0迭代到列数。

这是一个代码,它计算文件中矩阵的维度从文件中读取构造矩阵,然后打印

public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner (new File("data.txt"));
Scanner inFile = new Scanner (new File("data.txt"));
/*To get the dimension of the matrix*/
String[] line = sc.nextLine().trim().split("\s+");
int row = 1, column = 0;
column=line.length;
while (sc.hasNextLine()) {
row++;
sc.nextLine();
}
sc.close();
/*To read the matrix*/
int[][] matrix = new int[row][column];
for(int r=0;r<row;r++) {
for(int c=0;c<column;c++) {
if(inFile.hasNextInt()) {
matrix[r][c]=inFile.nextInt();
}
}
}
inFile.close();
/*To print the matrix*/
System.out.println(Arrays.deepToString(matrix));
}

最新更新