我在文本文件中有整数,全部用空格分隔。
我知道如何读取文件,但我不知道如何将整数放入数组中。我知道我必须在某个地方使用parseint
有人可以帮帮我吗?
阵列是4x4
整数是:
2 1 4 2
9 7 5 3
9 8 3 5
1 0 0 0
arr = new int [4][4];
IODialog input = new IODialog();
String location = input.readLine("Enter the full path of the configuration text file: ");
Scanner scn = null;
try
{
scn = new Scanner(new BufferedReader(new FileReader(location)));
int i, j=0;
String line = scn.nextLine();
String[] numbers = line.split(" ");
}
finally
{
if (scn != null) {
scn.close();
}
}
}
答案 0 :(得分:2)
这将是有帮助的,
int[][] a = new int[4][4];
BufferedReader br = new BufferedReader(new FileReader("path/to/file"));
for (int i = 0; i < 4; i++) {
String[] st = br.readLine().trim().split(" ");
for (int j = 0;j < 4; j++) {
a[i][j] = Integer.parseInt(st[j]);
}
}
答案 1 :(得分:1)
你走在正确的轨道上。
只需在阅读扫描仪的下一行后立即填写数组。
int[][] arr = new int[4][4];
String location = input.readLine("Enter the full path of the configuration text file: ");
scn = new Scanner(new BufferedReader(new FileReader(location)));
String line = scn.nextLine();
String[] numbers = line.split(" ");
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
arr[i][j] = Integer.parseInt(numbers[j]);
这将逐行读取您的输入,并在每行中插入整数以完成您的4x4数组。