I am getting the following error for a method in my program:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:945)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
at Question2.readArray(Question2.java:73)
at Question2.main(Question2.java:29)
This is the method where line 73 is located:
public static void readArray() throws FileNotFoundException {
int count2, lessThan, greatThan;
int[] numArray = new int[5];
try (Scanner myRead = new Scanner(new File("C:/Users/cgva1/Documents/COP 1000/Exam2.dat"))) {
count2 = 0;
lessThan = 0;
greatThan = 0;
System.out.println("Reading numbers from a file...");
System.out.println(" ");
System.out.println("The numbers are:");
while (myRead.hasNextLine()) {
numArray[count2] = myRead.nextInt();
System.out.println(numArray[count2]);
if (numArray[count2] < 5) {
lessThan = lessThan + 1;
} else {
greatThan = greatThan + 1;
}
count2 = count2 + 1;
}
System.out.println(Integer.toString(greatThan) + " of the numbers are greater than 5.");
System.out.println(Integer.toString(lessThan) + " of the numbers are 5 or less.");
}
}
Line 73 is numArray[count2] = myRead.nextInt();
The code is supposed to take in 5 numbers from 1 to 10, total those 5 numbers up, write to a file, read from a file and determine how many are above 5 and how many are below f (That is this method).
The code will take input of the 5 numbers, give a total, Write to a file and read the numbers from the same file and then I get the error before it executes the great than and less than part.
Any suggestions?
I thought count2 was getting and extra digit and therefore looking for an array element that doesn’t exist. I placed an IF statement if count2 < 5, then count2 = count2 +1
, but I still got the same error.