0

I need to change how my array is formatted to where it shows as a 20x20 square. Any ideas on best way to do this?

public class MyGrid {

public static void main(String[] args) throws IOException
{
    FileReader file = new FileReader("list.txt");
    int[] integers = new int [400];
    int i=0;
    try {
        Scanner input = new Scanner(file);
        while(input.hasNext())
        {
            integers[i] = input.nextInt();
            i++;
        }
        input.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    System.out.println(Arrays.toString(integers));
}

}

2 Answers2

1

The try-with-resources statement is nice; I suggest taking advantage of it to clean-up safely. I don't see any need for a FileReader with your Scanner (File is good enough). Then every 20 values you print a newline - otherwise print a space; then print the value. Like,

int[] integers = new int[400];
try (Scanner input = new Scanner(new File("list.txt"))) {
    int i = 0;
    while (input.hasNextInt()) {
        integers[i] = input.nextInt();
        if (i != 0) {
            if (i % 20 == 0) {
                System.out.println();
            } else {
                System.out.print(" ");
            }
        }
        System.out.printf("%03d", integers[i]);
        i++;
    }
} catch (Exception e) {
    e.printStackTrace();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

The simplest and fastest way to do this (for me) would be that:

public class MyGrid {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("list.txt");

        int[] integers = new int[400];
        int[][] table = new int[20][20];
        int m, n, i = 0;

        int tableWidth = table[0].length; // 20 in that case

        try {
            Scanner input = new Scanner(file);
            while(input.hasNext()) {
                int value = input.nextInt();
                integers[i] = value;
                
                m = i / tableWidth; // Row index
                n = i % tableWidth; // Column index
                table[m][n] = value;

                i++;
            }

            input.close();
        } catch(Exception e) {
            e.printStackTrace();
        }

        System.out.println(Arrays.toString(integers));
    }
}

Moreover, this code will adapt to any other table size (e.g. 500, 600 or 4237 elements).

CAUTION: this code will store data in a 2D array but it will not display it in the console. If you want to display data while reading file, I suggest you to look at @Elliott Frisch answer which is more adapted.

0009laH
  • 1,960
  • 13
  • 27