我有一个包含以下内容的文本文件:
0 12
1 15
2 6
3 4
4 3
5 6
6 12
7 8
8 8
9 9
10 13
Run Code Online (Sandbox Code Playgroud)
我想从data.txt文件中读取这些整数,并将这两列保存到Java中的两个不同的数组中.
我是Java的初学者,谢谢你的帮助.
除非你事先知道文件中的行数,否则我建议你收集两个数字Lists,例如ArrayList<Integer>.
像这样的东西应该做的伎俩:
List<Integer> l1 = new ArrayList<Integer>();
List<Integer> l2 = new ArrayList<Integer>();
Scanner s = new Scanner(new FileReader("filename.txt"));
while (s.hasNext()) {
l1.add(s.nextInt());
l2.add(s.nextInt());
}
s.close();
System.out.println(l1); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(l2); // [12, 15, 6, 4, 3, 6, 12, 8, 8, 9, 13]
Run Code Online (Sandbox Code Playgroud)
如果您确实需要两个int[]数组中的数字,则可以在之后创建数组(当大小已知时).
| 归档时间: |
|
| 查看次数: |
3590 次 |
| 最近记录: |