Adam
Adam

Reputation: 11

Switch is set to int arguments. Create the default case to also except strings so it does not read error

Below is an example of a switch statement with 3 cases and a default based on an int. I am wondering how I can have the default return the message "Error: Please Retry" and then loop again if something other than an int is entered? Currently if you enter any int, the program works fine. However, if you enter any other character besides an int - the build fails. Do I need to set up another case and then build another class to deal with this?
Thanks in advance.

int choice;                                              

while(true){                                                 

    System.out.println("Please enter the number of your choice:");
    System.out.println("1. Monitor A");
    System.out.println("2. Monitor B");
    System.out.println("3. Exit");
    choice = scanner.nextInt();                  

    switch(choice){                              
        case 1:                                      
            monitorA();
            break;
        case 2:     
            monitorB();                        
            break;
        case 3:          
            System.exit(0);
            break;
        default:                                            
            System.out.println("Error:  Please Retry");
            break;
    }
}

Upvotes: 0

Views: 355

Answers (2)

Jarlik Stepsto
Jarlik Stepsto

Reputation: 1725

With scanner.nextInt() you will get an exception if the next token is not an int.

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

(See Scanner.nextInt()).

int i = -1;

try{
    i = scanner.nextInt();
} catch(Exception e){
    //print error
}

//your switch case

Or you can use switch case with a string (since java 7).

String in = scanner.next();
switch(in){
    case '1': break;
    case '10': break;
    default: //print error;
}

Or you can read the next String and check, if it is an valid integer without exceptions

//read next string
String in = scanner.next();

//check if integer
if(!isInteger(in)){
    //print your error
}

int i = Integer.parse(in);

//HERE your switch case

isInteger from this Thread:

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

Upvotes: 2

Daniel Scott
Daniel Scott

Reputation: 7923

Presumably, if you enter a string, scanner.nextInt(); throws an exception? You can just catch it, print your message, and continue the loop.

Upvotes: 0

Related Questions