简体   繁体   中英

Iterating from a file to a 2d array in Java?

I am attempting to read in a file and generate a 2d array from the files contents.

I have the following as my instance variables and my constructor


private int[][] matrix;
    private boolean isSquare;

    //Constructors
    public MagicSquare(String filename)
    {
        try {
            Scanner scan = new Scanner(new File(filename));

            int dimensions = Integer.parseInt(scan.nextLine());
            int row = 0;
            int col = 0;
            this.matrix = new int[dimensions][dimensions];
            while (scan.hasNextLine())
            {
                String line = scan.nextLine();

                Scanner lineScan = new Scanner(line);

                while (row < dimensions)
                {
                    this.matrix[row][col++] = lineScan.nextInt();
                    row++;
                }
                lineScan.close();
            }


        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

when I try and run this through the testing software I end up with the following results

Expected :
             4              9              2 
             3              5              7 
             8              1              6 
Returned :
             4              0              0 
             0              9              0 
             0              0              2 

which is leading me to believe I am doing something wrong in my iteration any tips or hints as to where I should be looking?

You increment both the row and the column at effectively the same time, once for each number you read:

            while (row < dimensions)
            {
                this.matrix[row][col++] = lineScan.nextInt();
                row++;
            }

Instead, guard the loop on col , and increment row afterwards, and reset col to zero:

            while (col < dimensions)
            {
                this.matrix[row][col++] = lineScan.nextInt();
            }
            row++;
            col = 0;

Note that the loop is more cleanly written as a for loop:

            for (int col = 0; col < dimensions; ++col)
            {
                this.matrix[row][col] = lineScan.nextInt();
            }
            row++;

and you can also write your outer loop as a for loop as well:

for (int row = 0; scan.hasNextLine(); ++row)
// instead of while (scan.hasNextLine()) and incrementing row separately.

Ideone demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM