使用||在交换机的情况下?

时间:2014-02-03 05:26:41

标签: java switch-statement

因此,对于Java Fundamentals的大学实验室来说,我遇到了麻烦。我必须设置一个开关并在里面切换一个盒子。用户输入有3个选项,每个选项都可以用字母回答。问题是这封信被允许为大写或小写,而问题是我似乎无法弄清楚如何设置它以便一个案例允许其中任何一个。

在下面的代码中.crustType被定义为char。

请记住这是Java Fundamentals,我们只是学习切换,不幸的是我们的PPT并不能解释在这种情况下该怎么做。

switch (crustType)
  {
     case (crustType == 'H' || crustType == 'h'):
        crust = "Hand-tossed";
        System.out.println("You have selected 'Hand-Tossed' crust for your pizza.");
        break;

     case (crustType == 'T' || crustType == 't'):
        crust = "Thin-crust";
        System.out.println("You have selected 'Thin-Crust' crust for your pizza.");
        break;

     case (crustType == 'D' || crustType == 'd'):
        crust = "Deep-dish";
        System.out.println("You have selected 'Deep-Dish' crust for your pizza.");
        break;

     default:
        crust = "Hand-tossed";
        System.out.println("You have not selected a possible choice so a Hand-tossed crust was selected.");
  }

但是我一直收到错误|| ...

97: error: incompatible types
      case (crustType == 'H' || crustType == 'h'):
                             ^   required: char   found:    boolean 
102: error: incompatible types

3 个答案:

答案 0 :(得分:10)

使用:

case 'H':
case 'h':
    ...
    break;
case 'T':
case 't':
    ...
    break;

代替。由于crustType的类型为char,因此case中的内容必须为char类型。当你输入像

这样的东西时
crustType == 'H'

您将收到错误,因为该表达式返回boolean

答案 1 :(得分:5)

这是错误的,请使用如下

case 'H' :
case 'h' :
       crust = "Hand-tossed";
        System.out.println("You have selected 'Hand-Tossed' crust for your pizza.");
        break;
// Next set code case

这是一个陈述可以有多个案例标签的方式

答案 2 :(得分:0)

或者您可以使用if-else-if语句

if(crustType == 'H' || crustType == 'h'){
        crust = "Hand-tossed";
        System.out.println("You have selected 'Hand-Tossed' crust for your pizza.");
        }

     else if(crustType == 'T' || crustType == 't'){
        crust = "Thin-crust";
        System.out.println("You have selected 'Thin-Crust' crust for your pizza.");
        }

     else if(crustType == 'D' || crustType == 'd'){
        crust = "Deep-dish";
        System.out.println("You have selected 'Deep-Dish' crust for your pizza.");
        }

     else{
        crust = "Hand-tossed";
        System.out.println("You have not selected a possible choice so a Hand-tossed crust 
was selected.");
}

或if。

中的String.equalIgnoreCase方法

N.B。我更喜欢另一个答案..它只是一个替代方案:))