我尝试使用下面文本文件中的数字创建一个2D数组,但似乎我无法创建我的2D数组的最后两行。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test1 {
public static void main(String[] arg) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the file: ");
String name = sc.nextLine();
File inFile = new File(name);
int[][] table2 = reading(inFile);
printTable(table2);
System.out.println();
}
// scanning file
public static int[][] reading(File inFile) {
//Create the input stream.
Scanner in = null;
try {
in = new Scanner(inFile); // doesn't connect
} catch (FileNotFoundException e) {
System.out.println("File not found! Program will now exit!");
System.exit(1);
}
int i = 2;
int row = in.nextInt(); //reading the first integer for row
int col = in.nextInt(); //reading the first integer for column
int[][] data = new int[row][col];
System.out.println("row is " + row + " and col is " + col);
// turn data into array
while(in.hasNext() && i < data.length) {
for (int j = 0; j < data[i].length; j++){
data[i-2][j] = in.nextInt();
}
i++;
}
return data;
}
// display 2D array
public static void printTable(int[][] matrix) {
for (int row = 0 ; row < matrix.length ; row++) {
for (int col = 0 ; col < matrix[row].length ; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
这是文本文件。前两个数字是行数和列数
5
6
5
15
8
5
3
16
9
14
12
14
20
4
17
11
11
11
20
14
16
5
18
12
10
19
17
11
10
2
16
20