java - Java读取txt文件第一行的第一个整数

标签 java input io

我被困在这里...我有一个 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/

相关文章:

java - 在实现主UI线程中可运行的类的方法上设置计时器

c++ - 如何在不使用数组的情况下存储输入?

c++ - 如何使用 cout 打印 0x0a 而不是 0xa?

scala - 使用 sc.textfile 时读取文本文件的是驱动程序还是 worker ?

java - 如何将选定行的值替换为现有文件java

java - 如何与 BLE 通信

java - 寻找主机时如何设置套接字超时?

JavaFX : how to check for anti-aliasing support

c++ - 去除空格 (C++)

c++ - 基本字符串输入