this error seems to be a very common issue. I've looked up on other Stack Overflow posts that ask about this and tried to implement their solutions, but I'm still getting the same error. The complete error is:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at src.file.main(file.java:29)
I'm sure there's something really simple I'm missing, but I can't quite find it as when I read through my code, the logic seems good. This is my file:
public class file {
public static void main(String[] args) throws IOException {
int choice = 0;
Scanner myVal = new Scanner(System.in);
while(choice != 3) {
System.out.println("1. enter info \n2. print info \n3.exit");
System.out.println("Enter a choice: ");
choice = myVal.nextInt(); //Line 29
if(choice == 1) {
enterInfo();
}
else if(choice == 2) {
print();
}
else if(choice == 3) {
System.exit(0);
}
}
}
static ArrayList<newType> studInfo = new ArrayList<src.newType>();
static void enterInfo() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the information (Program year average lastname): ");
String info = keyboard.nextLine().trim();
if(info.isEmpty()) {
System.out.println("Error, no input was made.");
keyboard.close();
return;
}
String[] tokens = info.split(" ");
int size = tokens.length;
String prgm = tokens[0];
int yr = Integer.parseInt(tokens[1]);
String lastname = tokens[3];
Double avg = Double.parseDouble(tokens[2]);
newType inf = new newType(prgm, yr, avg, lastname);
studInfo.add(inf);
System.out.println("Information added.");
keyboard.close();
return;
}
Example input: math 5 76 Smith, this information is added to the arraylist of type newType
where it can be printed, or another profile can be added.
The program compiles without errors or warnings, and I can successfully run the program. When I choose option 1, I enter all the information, in the correct format, to which I get the information added
message, signaling it was a successful process. After this message, the exception appears. This leads me to believe the error doesn't actually lie within my enterInfo function, as I first thought, but rather when it reaches line 29 for the second time. I don't know how to fix this error, could anyone help? Thanks in advance!