switch条件选择结构
switch基本语法
switch(表达式){
case 值1:
代码块;
break;
case 值2:
代码块;
break;
case 值n:
代码块;
break;
default:
代码块;
}
在switch语句中 表达式是一个已经定义且赋值过的变量名
根据表达式的值执行不同的分支,具体来说,根据表达式的值找匹配的case,找到后执行后面的代码。
碰到break时结束整个switch的执行。
如果没有匹配的值则执行default中的语句
switch代码
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份");
int year = scanner.nextInt();
System.out.println("请输入月份");
int month = scanner.nextInt();
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println(year + "年" + month + "月有31天");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println(year + "年" + month + "月有30天");
break;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
System.out.println(year + "年" + month + "月有29天");
}else {
System.out.println(year + "年" + month + "月有28天");
}
break;
default:
System.out.println("输入的月份有误");
break;
}
}
}
表达式值的数据类型只能是 byte,short, int , char , 枚举 和 String
break是指跳出switch语句,执行switch后面的语句。每条case语句后面都应该跟break语句,否则的话它会继续执行后面case中的代码直到碰到break语句或switch结束.
case可以堆叠