【发布时间】:2015-08-29 03:11:49
【问题描述】:
所以基本上我正在尝试读取包含以下内容的 .txt 文件:
3 5
2 3 4 5 10
4 5 2 3 7
-3 -1 0 1 5
并将它们存储到二维数组中并在控制台上打印,我从控制台得到的结果很好,但只缺少第一行 3 5,我不知道我的代码有什么问题使它忽略了第一行。 我现在得到的输出:
2 3 4 5 10
4 5 2 3 7
-3 -1 0 1 5
import java.io.*;
import java.util.*;
public class Driver0 {
public static int[][] array;
public static int dimension1, dimension2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Project 0.");
System.out.println("What is the name of the data file? ");
String file = input.nextLine();
readFile(file);
}
public static void readFile(String file) {
try {
Scanner sc = new Scanner(new File(file));
dimension1 = sc.nextInt();
dimension2 = sc.nextInt();
array = new int[dimension1][dimension2];
while (sc.hasNext()) {
for (int row = 0; row < dimension1; row++) {
for (int column = 0; column < dimension2; column++) {
array[row][column] = sc.nextInt();
System.out.printf("%2d ", array[row][column]);
}
System.out.println();
}
}
sc.close();
}
catch (Exception e) {
System.out
.println("Error: file not found or insufficient requirements.");
}
}
}
【问题讨论】:
-
你会错过前两个数字,因为你在这两行中得到它们:
dimension1 = sc.nextInt()和dimension2 = sc.nextInt(),你将它们用作数组的维度。
标签: java arrays multidimensional-array