Java中的控制语句和C语言大同小异,if-else ,while,do-while,以及 for 循环都基本相同。
这里重点复习一下switch 多选择结构。
switch语句一般只用来做多值的判断,是一种比较简单的表达方法。
switch语句会根据表达式的值从相匹配的case标签处开始执行,一直执行到break语句处或者是switch语句的末尾。如果表达式的值与任一case值不匹配,则进入default语句(如果存在default语句的情况)。
举例,实践是最好的学习方法,举上两个例子,知识全在例子里:
例一:
/**
* switch例子
* @author 房廷飞
*
*/
public class TextSwitch {
public static void main(String[] args){
int month =(int)(1+12*Math.random()); //强制类型转换,取1-12的随机数
System.out.println("月份:"+ month);
switch (month) { //switch后加变量或条件表达式
case 1: //case最好与switch对其
System.out.println("一月份,过新年!");
break; //到break退出判断,一定要有break!否则还向下执行!
case 2:
System.out.println("二月份,开春了!");
break;
case 3:
System.out.println("三月份,——————");
break;
case 4:
System.out.println("四月份,——————");
break;
default: //default:未列举的其他情况
System.out.println("我是其他月份!");
break;
}
}
}
例二:
public class Switch2 {
public static void main(String[] args) {
char c = 'a';
int rand = (int) (26 * Math.random());
char c2 = (char) (c + rand);
System.out.print(c2 + ": ");
switch (c2) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println("元音");
break; //前面的a,e,i,o,u全都到此(break)结束!
case 'y':
case 'w':
System.out.println("半元音");
break;
default:
System.out.println("辅音");
}
}
}
2019-02-13 17:49:31 房廷飞