【问题标题】:Menu selection with if else and switch使用 if else 和 switch 进行菜单选择
【发布时间】:2015-02-19 18:14:23
【问题描述】:

您好,我正在编写具有 5 种操作选择的计算器。

1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit

我想请用户对操作进行选择,检查选择是否有效(即1-5)如果没有,则给出错误信息并提示用户再次选择。

我正在考虑在 else 语句中使用 if-else 语句和 switch 语句。

System.out.printf("What would you like to do? ");
int selection = input.nextInt();

if  (selection!=1 || 2 || 3 || 4 || 5) {  

    System.out.println("You have entered an invalid choice, please re-enter      
    your choice: ");
}/*end if    as long as the selection is NOT a 1 - 5, prompt the user to 
 re-enter*/

else {
    switch(selection){

        case 1:
        case 2:
        case 3:
        case 4:
        case 5;

我在 if 行收到 Eclipse 编译器错误: The operator || is undefined for the argument type(s) boolean, int

任何想法什么是错的以及如何解决这个问题?谢谢

开尔文

【问题讨论】:

    标签: java eclipse if-statement switch-statement


    【解决方案1】:

    你甚至不需要if 声明

    switch(selection){
        case 1:
        // handle 1
            break;
        case 2:
        // handle 2
            break;
        case 3:
        // handle 3
            break;
        case 4:
        // handle 4
            break;
        case 5:
        // handle 5
            break;
        default:
            System.out.println("You have entered an invalid choice, please re-enter      
    your choice: ");
            break;
    }
    

    default 子句将处理不适合任何情况的每个语句。

    【讨论】:

      【解决方案2】:

      if 语句需要条件运算符之间的有效表达式。也许

      if (selection != 1 && selection != 2 && selection != 3
              && selection != 4 && selection != 5) {
         ...    
      }
      

      【讨论】:

        【解决方案3】:

        您不能像在英语中那样在 Java 中组合条件案例。 “如果选择不是 1 或 2 或 3 或 4 或 5”不能以这种方式翻译成 Java。您必须每次都显式声明selection,否则编译器会认为您正试图在selection != 1boolean2int)上使用|| 运算符,因此会出现错误。此外,该值始终为“非 1”“非 2”...您应该使用“和”(&&)。

        if (selection!=1 && selection!=2 && selection!=3 && selection!=4 && selection!=5) {
        

        这可以简化,因为数字是连续的:

        if (selection < 1 || selection > 5)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-06
          • 1970-01-01
          • 1970-01-01
          • 2015-06-27
          • 1970-01-01
          • 2012-10-15
          相关资源
          最近更新 更多