Click here to Skip to main content
15,887,338 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
import java.util.Scanner;

public class Menu {
     public static Scanner scanner = new Scanner(System.in);
    
    public static int inputInt(String msg){
        int data;
            System.out.print( msg);
            data= Integer.parseInt(scanner.nextLine());
      
        return data;
    }
    public static void main(String[] args) {
        y1 f1 = new y1();
        y2 f2 = new y2();
        y3 f3 = new y3();

        int option = -1;
        do {
            System.out.println("----- MENU -----");
            System.out.println("1. y1");
            System.out.println("2. y2");
            System.out.println("3. y3");
            System.out.println("0. Exists");
 
            option = inputInt("Enter your choice: ");

            switch (option) {
                case 1:
                    f1.findS();
                    break;
                case 2:
                    
                    f2.check();
                    break;
                case 3:                    
                    f3.seriesOfPrimeNum();
                    break;
                case 0:
                    System.out.println("Exist program. Goodbye!!");
                    break;
                default:
                    System.out.println("Wrong input ! Please enter again ");
            }
        }  while (option != 0);
    }
}


What I have tried:

When I enter a character or string for option it outputs an error, whereas in the inputInt function I convert String to Int already
Posted
Updated 18-Jul-23 5:30am
Comments
Richard MacCutchan 18-Jul-23 11:33am    
I just tried that and it seems to work fine. You need to provide more details.

1 solution

Because the string or character you entered isn't a numeric digit: if it isn't, it can't be parsed to a number!
Put a while loop around the print and parseInt calls, and a try ... catch block as well. Move your return to after the parseInt call, and it will loop until the user enters a number.
Java
while(true) {
   try {
      ...your stuff...
      return data;
   }
   catch(Exception e) {}
}


Also, see here: Java.util.Scanner.nextInt() Method | Tutorialspoint[^]
Replace this:
Java
data= Integer.parseInt(scanner.nextLine());

With this:
Java
data= scanner.nextInt();
And let the system do the work.
 
Share this answer
 
Comments
CPallini 19-Jul-23 2:57am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900