This is my code: I am trying to make a function that allows a user to return to the menu once they have finished with the program. However, I keep getting the 'NoSuchElement' error whenever I try to run the code.
import java.io.FileNotFoundException;
import java.util.Scanner;
public class homePage
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner sc = new Scanner (System.in);
Menu.menu();
System.out.println("Would you like to 1:Exit the program or 2: complete another action ");
int newChoice = sc.nextInt();
System.out.println(newChoice);
switch(newChoice)
{
case 1:
Exit exitScreen = new Exit();
exitScreen.exit();
break;
case 2:
Menu.menu();
default:
System.out.println(newChoice + "invalid input");
System.out.println("\n");
main(args);
}
}
}
The output:
Would you like to 1:Exit the program or 2: complete another action
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 homePage.main(homePage.java:12)
Here is a Minimal, Reproducible Example This refers to the menu class. When the user selects one of the options it is print out the word (display/create/delete) then it should ask the user if they are finished. If they are finished, they will be shown an exit message and if they aren't finished the menu should be displayed again.
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Menu
{
public static void menu() throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
System.out.println("Menu \n1 - Display \n2 - Create \n3 - Delete");
int choice = in.nextInt();
System.out.println(choice);
switch (choice)
{
case 1:
System.out.println("Display");
case 2:
System.out.println("Create");
case 3:
System.out.println("delete");
break;
default:
System.out.println("Incorrect Value. Enter a value between 1 and 3");
break;
}
in.close();
}
}