прочитать первое целое число в первой строке текстового файла в Java - PullRequest
0 голосов
/ 21 сентября 2018

Я застрял здесь ... У меня есть текстовый файл с несколькими (int) 2D-массивами, разделенными пробелом.первая строка, которая предшествует каждому двумерному массиву, является размером массива(2D массивы возводятся в квадрат: #rows = #columns = dim)

4

1 2 3 4

5 6 7 8

1 2 34

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 голосов
/ 21 сентября 2018

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

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

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

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

12 3 4

5 6 7 8

вывод

1 2 3 4

5 6 7 8

1 23 4

5 6 7 8

, затем я проверил это с помощью этого ввода:

4

1 2 3 4

56 7 8

1 2 3 4

5 6 7 8

5

0 1 2 3 4

5 6 78 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...