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

时间:2018-09-21 01:59:30

标签: java input io

我被困在这里...我有一个txt文件,其中包含几个(整数)二维数组,中间用空格分隔。每个2D数组之前的第一行是数组的尺寸。 (二维数组是平方的:#rows = #columns = dim)

4

1 2 3 4

5 6 7 8

1 2 3 4

5 6 7 8

在这一阶段,我希望能够在第一行读取数组的维数(dim = 4)。将文件中的2D数组放到2D数组中并显示

如何在第一行获取整数?有见识吗? 这是我到目前为止所拥有的:

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();

2 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案。

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

答案 1 :(得分:0)

我相信这就是您想要做的吗?

该程序不是手动为dim赋值,而是从文件中读取dim

int dim = scan.nextInt();

这是完整的代码。

public class Main2 {
    public static void main(String[] args) throws FileNotFoundException {

        File fileInput = new File("file.txt");

        Scanner scan = new Scanner(fileInput);

        int dim = scan.nextInt(); //this value should be read from the first line

        int[][] array = new int[dim][dim];

        while (scan.hasNext()) {
            for (int row = 0; row < dim; row++) {
                for (int column = 0; column < dim; column++) {
                    array[row][column] = scan.nextInt();
                }
            }

        }
        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();
        }
    }
}
相关问题