Skip to content
Advertisement

How can i make my turn my text file to 40×40 matrix [closed]

In my code i need to read my text file and create a 40×40 matrix however my array only reads the first line Here is my code;

    String worldData = "world.txt";
    File worldFile = new File(worldData);
    int[][] worldArray = new int[40][40];
    Scanner scanner = new Scanner(worldFile);
    while (scanner.hasNextLine()) {
        String allText = scanner.nextLine();
        String[] allLines = allText.split(";");
        for (int i = 0; i < worldArray.length; i++) {
            for (int j = 0; j < worldArray[0].length; j++) {

                worldArray[i][j] = Integer.parseInt(allLines[0]);
            }
        }

Advertisement

Answer

Assuming that every line contains a row of the world matrix, the for-i loop should read exactly one line.

Scanner scanner = new Scanner(worldFile);
for (int i = 0; i < worldArray.length; i++) {
    if (!scanner.hasNextLine()) {
        throw new IllegalArgumentException("There are only " + i
               + " lines of the 40 needed.");
    }
    String line = scanner.nextLine();
    String[] cells = line.split(";");
    if (cells.length != 40) {
        throw new IllegalArgumentException("There are " + i
               + " cells instead of the 40 needed.");
    }
    for (int j = 0; j < worldArray[0].length; j++) {
        worldArray[i][j] = Integer.parseInt(cells[j]);
    }
}

Alternatively you can do without a Scanner:

String worldData = "world.txt";
Path worldFile = Paths.get(worldData);
List<String> lines = Files.readAllLines(worldFile, StandardCharsets.UTF_8);
if (lines.size() < 40) {
    throw new IllegalArgumentException("There are only "
            + lines.size()
           + " lines of the 40 needed.");
}
for (int i = 0; i < worldArray.length; i++) {
    String line = lines.get(i);
    String[] cells = line.split(";");
    if (cells.length != 40) {
        throw new IllegalArgumentException("There are " + i
               + " cells instead of the 40 needed.");
    }
    for (int j = 0; j < worldArray[0].length; j++) {
        worldArray[i][j] = Integer.parseInt(cells[j]);
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement