当有人输入一个字母作为菜单选项时输出错误信息?

时间:2012-12-26 18:30:29

标签: java

这个程序运作良好,但我想让这个程序告诉用户不应该使用任何字母只有选项1到5.有人可以帮我解决这个问题吗?

public class Main {

Scanner input = new Scanner ( System.in );

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
int UserIn=0;
double numberInputA;
double numberInputB;
double Answer;


Scanner input = new Scanner( System.in );

while (UserIn!=5){ //this starts while loop when user input is not equal to 5
System.out.println ("What type of calculation would you like to perform?");
System.out.println ( "1. Add\n2. Subtract\n" +
"3. Multiply\n4. Divide\n5. Exit");//shows the menu
UserIn = input.nextInt();//ask user to input integer of choice

if (UserIn>5){
System.out.println( "ERROR choose the numbers on the menu" );
}else if (UserIn<1){
    System.out.println("ERROR choose the numbers on the menu");
} 

1 个答案:

答案 0 :(得分:0)

public static void main(String[] args) {
    // TODO code application logic here
    int UserIn = 0;
    double numberInputA;
    double numberInputB;
    double Answer;

    while (UserIn != 5) { //this starts while loop when user input is not equal to 5
        System.out.println("What type of calculation would you like to perform?");
        System.out.println("1. Add\n2. Subtract\n"
                + "3. Multiply\n4. Divide\n5. Exit");//shows the menu
        UserIn = getUserInput();
    }
}

private static int getUserInput() {
    int UserIn = 0;
    Scanner input = new Scanner(System.in);
    try {
        UserIn = input.nextInt();//ask user to input integer of choice
        if (UserIn > 5) {
            System.out.println("ERROR choose the numbers on the menu");
            return -1;
        } else if (UserIn < 1) {
            System.out.println("ERROR choose the numbers on the menu");
            return -1;
        }
        return UserIn;
    } catch (Exception ex) {
        System.out.println("ERROR only numbers are allowed");
        return -1;
    }
}