我被困在这里...我有一个 txt 文件,其中有一些用空格分隔的(int)二维数组。每个二维数组前面的第一行是数组的维度。 (二维数组是平方的:#rows = #columns = dim)
4
1 2 3 4
5 6 7 8
1 2 3 4
5 6 7 8
在这个阶段,我希望能够在第一行读取数组的维度(dim =4)。将文件中的二维数组放入二维数组并显示
如何获取第一行的整数?有什么见解吗? 这是我到目前为止所拥有的:
Scanner scan = new Scanner(new File(fileInput));
dim= 4; //this value should be read from the first line
array = new int[4][4];
while (scan.hasNext()) {
for (int row = 0; row < dim; row++) {
for (int column = 0; column < dim; column++) {
array[row][column] = scan.nextInt();
System.out.print(array[row][column]);
}
System.out.println();
}
}
scan.close();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[i][j]);
}
System.out.println();
最佳答案
这是一个可能的解决方案。
String fileInput = "input.txt";
Scanner scan = new Scanner(new File(fileInput));
int dim = 1;
int[][] array = null;
int counter = 0;
while (scan.hasNext())
{
if (counter++ == 0)
{
dim = scan.nextInt();
array = new int[dim][dim];
continue;
}
int i = (counter-2)/dim ;
int j = (counter-2)%dim ;
array[i][j] = scan.nextInt();
if (i == dim - 1 && j == dim - 1 )
{
counter = 0;
for (i = 0; i < dim; i++)
{
for (j = 0; j < dim; j++)
{
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
scan.close();
我用你的输入测试了它
4
1 2 3 4
5 6 7 8
1 2 3 4
5 6 7 8
输出为
1 2 3 4
5 6 7 8
1 2 3 4
5 6 7 8
然后我用这个输入测试了它:
4
1 2 3 4
5 6 7 8
1 2 3 4
5 6 7 8
5
0 1 2 3 4
5 6 7 8 9
0 1 2 3 4
5 6 7 8 9
0 1 2 3 4
输出是
1234
5678
1234
5678
01234
56789
01234
56789
01234
关于java - Java读取txt文件第一行的第一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52435584/