问题
So for a college lab for Java Fundamentals I'm having trouble. I have to set up a switch and inside that switch a case. There are 3 options for user input, and each option can be answered with letter. The problem is that this letter is allowed to be capital OR lower case, and the problem is I cant seem to figure out how to set it up so a case will allow either of those.
In the code below..crustType is defined as a char.
Keep in mind this is Java Fundamentals and we're just learning about switches, unfortunately our PPT for this doesn't explain what to do in this situation.
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.");
}
However I keep getting an error with ||...
97: error: incompatible types
case (crustType == 'H' || crustType == 'h'):
^ required: char found: boolean
102: error: incompatible types
回答1:
Use:
case 'H':
case 'h':
...
break;
case 'T':
case 't':
...
break;
instead. Since the type of crustType
is char
, then what goes in case
s must be of char
type. When you put something like
crustType == 'H'
you will get an error because that expression returns a boolean
.
回答2:
It's wrong, Use like below
case 'H' :
case 'h' :
crust = "Hand-tossed";
System.out.println("You have selected 'Hand-Tossed' crust for your pizza.");
break;
// Next set code case
This is how a statement can have multiple case labels
回答3:
or you can use if-else-if
statements
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.");
}
or a String.equalIgnoreCase
method in the if .
N.B. i would prefer the other answer .. it is just an alternative :)
来源:https://stackoverflow.com/questions/21520252/using-in-cases-in-a-switch