прочитайте первое целое число первой строки txt файла в Java

1 ApisMel [2018-09-21 04:59:00]

Я застрял здесь... У меня есть в txt файле с несколькими (int) 2D-массивами, разделенными пробелом. первая строка, которая предшествует каждому двумерному массиву, представляет собой размерность массива. (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();

java input io


2 ответа


0 Hakanoreaver [2018-09-21 06:08:00]

Я считаю, что это делает то, что вы хотели сделать?

Вместо того, чтобы вручную назначать значение 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();
        }
    }
}

0 dariusiv [2018-09-21 06:05:00]

Вот возможное решение.

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