For the past few days I have been working on a project for my class and keep running into this same error repeatedly. I am working in visual studio code and the goal of the project is to make the game of life using methods and scanning .txt files. This same error message keeps showing up whenever I try to compile the code. Here is the code in question:
import java.io.*;
import java.util.Scanner;
public class GameOfLife3 {
public static final char ON = 'X';
public static final char OFF = '*';
public static int fileRow, fileColumn;
public static int array[][];
public static char board[][];
public static char nextBoard[][];
public static int nextArray[][];
public static Scanner scan = new Scanner(System.in);
public static int[][] readGrid(String fileName) throws IOException{
File file = new File(fileName);
Scanner scan2 = new Scanner(file);
fileRow = scan2.nextInt();
fileColumn = scan2.nextInt();
array = new int[fileRow][fileColumn];
for(int i = 0; i < fileRow; i ){
for(int j = 0; j < fileColumn; j ){
array[i][j] = scan2.nextInt();
}
}
return array;
(there is more code in between here but thats not the part I am having trouble on)
public static void main(String[] args) throws IOException{
String fileName;
System.out.print("Please enter the name of the file you want to use (name.txt): ");
fileName = scan.nextLine();
array = readGrid(fileName);
}
}
I know its pretty messy but I am going to fix it later.
Also here is the the .txt file i am trying to use. (name is Blinker.txt)
5 5
00000
00000
01110
00000
00000
Some stuff I tried to do was use the .hasNextInt() function to check for when the .txt but it did not work. Any help would be greatly appreciated.
CodePudding user response:
The NoSuchElementException
is not a compilation error - it is an exception that is thrown at runtime. (The Java compiler cannot known how many values your input file contains and therefore cannot report such an error.)
And to me it is clear why it is thrown: you read the two integers 5 and 5 from the file and then try to read another 25 integer values from the file - but your file contains (after those two values) only 5 values: 0, 0, 1110, 0 and 0.
nextInt()
is not the right method to read in your data. Instead of that you should use next()
(to read a string containing 0s and 1s) and then split them:
for (int i = 0; i < fileRow; i ) {
String s = scan2.next();
for (int j = 0; j < fileColumn; j ) {
array[i][j] = Integer.parseInt(s.substring(j, j 1));
}
}