如何在switch语句中添加条件?(例如: - 显示平均分数的等级)
答案 0 :(得分:6)
我建议使用if-else ... switch
语句只能比较相等。
使用整数分数,您可以执行类似......
的操作switch (score)
{
case 100:
case 99:
case 98:
case 97:
case 96:
case 95:
case 94:
case 93:
case 92:
case 91:
case 90:
grade = 'A';
break;
case 89:
/* ... */
}
看到问题? : - )
答案 1 :(得分:1)
你做不到。使用if-else-if-else。
答案 2 :(得分:1)
根据您的范围,您可以使用公式。 e.g。
switch(score/10) {
case 10: case 9: case 8: return 'A';
case 7: return 'B';
case 6: return 'C';
case 5: return 'D';
default: return 'U';
}
答案 3 :(得分:1)
以下是我如何在switch语句中使用小于大于的值。以下是动作3 ...
var unknown1:Number = 8;
var unknown2:Number = 2;
var lowerBoundary = 1;
var upperBoundary = 5
开关(真){
case (unknown2 < lowerBoundary || unknown2 > upperBoundary):
trace("value is out of bounds");
break;
case (unknown2 > lowerBoundary && unknown2 < upperBoundary):
trace("value is between bounds");
break;
default:
trace("Out of Luck");
break;
}
...输出 值在边界之间
答案 4 :(得分:0)
此问题列出了Java标记,所以......
通用开关声明:
// ... within class scope
private final int CONSTANT_1 = 1;
private final int CONSTANT_2 = 2;
private final int CONSTANT_3 = 3;
// ...
public void doStuff(MyObject myObject){
int variable = myObject.getIntValue();
switch(variable){
case CONSTANT_1:
System.out.println(variable + " is equal to " + CONSTANT_1);
// use a break statement to tell the switch to stop here
// or else it will execute all subsequent cases:
break;
case CONSTANT_2:
System.out.println(variable + " is equal to " + CONSTANT_2);
// what happens if I leave out the break?
case CONSTANT_3:
System.out.println(variable + " is equal to " + CONSTANT_2);
break;
default:
System.out.println(variable + " wasn't equal to anything!");
}
假设我运行了3次,“myObject.getIntValue()”按此顺序返回这些值; 3,1,2和最后42.然后将生成以下输出: 第一次使用值'3'...
3等于3
第二次使用值'1'......
1等于1
第三次使用值'2'......
2 is equal to 2 2 is equal to 3
第四次使用值'42'......
42不等于什么!
注意第三次运行有两行(一行不正确),因为我省略了第二种情况的break关键字。
现在在Java 1.5及更高版本中,您还可以打开Enum类型:
public void doStuff(MyObject myObject){
MyEnumType varType = myObject.getEnum();
switch(varType){
case MyTypeOne:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
case MyTypeTwo:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
case MyTypeThree:
// everything else is the same -- nothing special here.
// put whatever code you want in.
break;
default:
// code for unknown case goes here
}
}
答案 5 :(得分:0)
在这个例子中,代码是否生成一个随机数,如果它是那个数字或那个数字就做一些事情。
int num; //Just declares a variable
Random r = new Random(); //This makes an object that generates random numbers.
num = r.nextInt(2); //This "Choose" the random number. The possible numbers are 0 and 1. and the sets the the num variable to the number.
switch(num){
case 0: //This says if the number is 0 then do this.
//put code here.
break;
case 1: //This says if the number is 1 then do this.
//put code here
break;
}
这是一个switch语句,根据随机选择的数字执行不同的操作。