您可能应该使用BufferedReader
and split
。这样做的好处是您知道在第二维中制作数组有多大,因为该split
方法将返回一个数组,您可以检查它length
:
public static void main(String[] args) throws Exception {
final String s = "5\n"
+ "9 6\n"
+ "4 6 8\n"
+ "0 7 1 5";
final InputStream is = new ByteArrayInputStream(s.getBytes());
final int[][] array = new int[4][];
try (final BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
for (int i = 0; (line = br.readLine()) != null; ++i) {
final String[] tokens = line.split("\\s");
final int[] parsed = new int[tokens.length];
for (int j = 0; j < tokens.length; ++j) {
parsed[j] = Integer.parseInt(tokens[j]);
}
array[i] = parsed;
}
}
System.out.println(Arrays.deepToString(array));
}
输出:
[[5], [9, 6], [4, 6, 8], [0, 7, 1, 5]]
由于数组不会扩展,因此在while
您不知道其大小的循环中使用它们并不容易。Usingsplit
允许您简单地使用您无法做到final int[] parsed = new int[tokens.length];
的Scanner
过度空白来执行此操作。
第一个维度大小是硬编码的,但是正如您所说的,您的文件总是有 4 行。