Java 如何将If语句转换为switch语句?
考虑到我在这里使用了两个变量,并且我试图解决它,但不起作用,如何将这个if语句转换为switch语句Java 如何将If语句转换为switch语句?,java,Java,考虑到我在这里使用了两个变量,并且我试图解决它,但不起作用,如何将这个if语句转换为switch语句 int child; char gender; int temp; child=console.nextInt(); gender=console.next().charat(0); if(gender=='m' && children>=4) temp =1; else if(gender=='m' && children<4) temp =
int child;
char gender;
int temp;
child=console.nextInt();
gender=console.next().charat(0);
if(gender=='m' && children>=4)
temp =1;
else if(gender=='m' && children<4)
temp =2;
else if(gender=='f' && children<4)
temp =3;
else
temp=4;
}
int-child;
性别;
内部温度;
child=console.nextInt();
性别=console.next().charat(0);
如果(性别=='m'&&children>=4)
温度=1;
else if(性别=='m'&&childrenswitch(性别){
}你应该先看看
switch语句基本上是针对每种情况计算一个条件。您可以使用下拉条件,但这需要很多额外的代码
例如,像
switch (gender) {
case 'm':
temp = 0;
if (children >= 4) {
temp += 1;
} else {
temp += 2;
}
break;
case 'f':
temp = 2;
if (children >= 4) {
temp += 2;
} else {
temp += 1;
}
break;
}
switch (gender) {
case 'm':
temp = 0;
switch (children) {
case 0:
case 1:
case 2:
case 3:
temp += 2;
break;
default:
temp += 1;
}
break;
case 'f':
temp = 2;
switch (children) {
case 0:
case 1:
case 2:
case 3:
temp += 1;
break;
default:
temp += 2;
}
break;
}
将生成与您的if
语句相同的结果
如果您喜欢使用纯switch
语句,您可以执行以下操作
switch (gender) {
case 'm':
temp = 0;
if (children >= 4) {
temp += 1;
} else {
temp += 2;
}
break;
case 'f':
temp = 2;
if (children >= 4) {
temp += 2;
} else {
temp += 1;
}
break;
}
switch (gender) {
case 'm':
temp = 0;
switch (children) {
case 0:
case 1:
case 2:
case 3:
temp += 2;
break;
default:
temp += 1;
}
break;
case 'f':
temp = 2;
switch (children) {
case 0:
case 1:
case 2:
case 3:
temp += 1;
break;
default:
temp += 2;
}
break;
}
Java的switch语句不支持范围:(“我试图解决它,但不起作用”
--您的尝试在哪里?始终将此与您的问题一起发布,并告诉我们它导致的任何错误和不当行为。switch
不支持范围=4
,因此您将有一个如果语句在其中的某个地方,这对您有帮助吗?您应该保持原样。switch
不适合。您的内部开关需要添加中断。@PaulBoddington这很有趣,我确信测试正确,不知道我在看什么:P