• 手机版

switch语句怎么用

100人浏览   2024-12-15 10:19:28

/**

* 测试switch语句的用法

*/

public class TestSwitch01 {

public static void main(String[] args) {

int grade = (int)(4*Math.random()+1);

switch (grade){

//switch()括号内的值默认int型,char和String字符串也可以使用

case 1:

//如果grade为1 执行下面语句

System.out.println("大一");

break;

//遇到break结束switch语句

case 2:

System.out.println("大二");

break;

case 3:

System.out.println("大三");

break;

default:

System.out.println("大四");

}

//和if同理 switch在多值判断的时候比if清晰

if (grade==1){

System.out.println("1");

} else if (grade==2) {

System.out.println("2");

} else if (grade==3) {

System.out.println("3");

}else {

System.out.println("4");

}

int month = (int)(12*Math.random()+1);

switch (month){

case 1:

case 2:

case 3:

//1和2不写break会沿用3的语句,相当于if month<=3

System.out.println("第一季度");

break;

case 4:

case 5:

case 6:

System.out.println("第二季度");

break;

case 7:

case 8 :

case 9:

System.out.println("第三季度");

break;

default:

System.out.println("第四季度");

}


char d1 = 'a';

switch (d1){

case 'a':

System.out.println('a');

break;

default:

System.out.println('b');

}


String d2 = "起飞";

switch (d2){

case "起飞":

System.out.println("起飞");

break;

default:

System.out.println("芜湖");

}

}

}