Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling with wrong User Input Java

I need help Using Exception handling with Wrong User Input. I am creating a text based game that welcomes the User and then goes to the main menu. It then tell the User the options, and then look for User input. For some Reason, whenever I input 1 or 2, It says: "Your input is invalid, please try again" And goes back to the choices. I don't know exactly where I am going wrong, hopefully someone can help me. Also, it won't catch the Mismatch Exception either. Hope you can Help! Thanks, Shandan

   public static void main(String[] args) {



    System.out.println("Welcome to Spec Ops!");
    System.out.println("Please state your name:");
    Scanner name = new Scanner(System.in);
    String Name = name.next();

    System.out.println("Hello "+Name);
    mainMenu();

    }


public static void mainMenu() {

    System.out.println("1. Story Mode");
    System.out.println("2. Infinant Combat");



    Scanner input = new Scanner(System.in);



    Object Selection = input.nextInt();

    boolean validOption = true;
    Integer x;


    try {
    x = (Integer)Selection;
    } catch(ClassCastException cce){
        System.out.println("Your input is invalid, please try again");
        validOption = false;
    } catch(InputMismatchException ime){
        System.out.println("Your input is invalid, please try again");
        validOption = false;

    }


if(validOption) {
    System.out.println("Hello!");
}

else {
    mainMenu();
}

}

}

like image 206
Shandan Spencer Avatar asked Feb 22 '26 10:02

Shandan Spencer


1 Answers

Scanner.nextInt returns ant int, so there is no need to go Object selection = scanner.nextInt(), and then cast to an int, you can merely have int selection = scanner.nextInt() and surround that in a try catch that chatches java.util.InputMismatchException, which is the exception thrown when the user types a letter and not an number

like image 194
w4etwetewtwet Avatar answered Feb 24 '26 01:02

w4etwetewtwet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!