[英]Switch statement
如何在switch语句中添加条件?(例如:-显示平均分数的等级)
我建议使用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:
/* ... */
}
看到问题了吗? :-)
这是我在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;
}
输出...值在界限之间
你不能 使用if-else-if-else。
根据您的范围,可以使用公式。 例如
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';
}
在此示例中,代码是否生成了一个随机数,如果是该数字或该数字,则执行某些操作。
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语句,它根据随机选择的数目执行不同的操作。
该问题带有Java标记,因此...
通用switch语句:
// ... 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.