0

I have an assignment that I need to validate that an input (String) is valid and if not throw an exception. When I have my there is a menu option (1-6) and when they select 2, which is to enter a new monkey it will skip the user entering input and jump straight to the error. If i move my variable after the try{ then it still doesnt allow any input and has an error because this variable is needed lower down. Any help of how to get this to work would be great. Thanks

public static void intakeNewMonkey(Scanner scanner) {
    
    System.out.println("What is the monkey's name?");
    String monkeyName = scanner.nextLine();
    
    try{
        
        if(!monkeyName.matches("^[a-zA-Z]+$")){
            throw new Exception("is wrong input!");
        }else{
            System.out.println("perfect!");
        }
    }catch(Exception e){
        System.out.println(e.toString());
    }
    
    
  • 1
    Without knowing what you need the `monkeyName` for after the `try/catch` your best course of action is to initialize `String monkeyName = null;` (or Optional) before the try/catch then check it after. – kendavidson Jun 16 '22 at 00:33

2 Answers2

0

Declare the monkeyName before the try block then you will be able to use if after the try...catch block.

System.out.println("What is the monkey's name?");
String monkeyName = null;

try{
    monkeyName = scanner.nextLine();
    
    if(!monkeyName.matches("^[a-zA-Z]+$")){
        throw new Exception("is wrong input!");
    }else{
        System.out.println("perfect!");
    }
}catch(Exception e){
    System.out.println(e.toString());
}

// use monkeyName here.
0

You haven't posted a minimal, reproducible example but I'm guessing that the problem is not in the code you posted but in the code that you didn't post.

You say that your application has a menu and the user selects a menu option by entering a number. So I assume that you use method nextInt for accepting the user selection and then you immediately call your intakeNewMonkey method and pass it the same Scanner that you use to get the user's menu selection. In that case, the call to method nextLine, in method intakeNewMonkey, is reading the newline that was entered by the user when she hit ENTER after entering the menu selection. Hence variable monkeyName is an empty string – which is not valid – and that causes the exception to be thrown.

After calling nextInt and before calling nextLine (to receive more input from the user), you need to call nextLine to get rid of the unwanted newline. Refer to this SO question: Scanner is skipping nextLine() after using next() or nextFoo()?

If my description of your application is correct, then in the code that accepts the user's menu selection, after calling method nextInt and before calling intakeNewMonkey I would add a call to nextLine (and ignore the value it returns).

Abra
  • 19,142
  • 7
  • 29
  • 41