在多分支的选择结构当中,我们除了使用嵌套的if语句,还可以使用一种switch语句
语法结构:
switch(表达式) {
case 值1: 语句块1;
break;
case 值2: 语句块2;
break;
… …
case 值n: 语句块n;
break;
default:
语句块n+1;
}
还记得在学习if嵌套过程中的月份天数案例吗?这里我们使用switch-case结构编程实现给出年份和月份,输出该某年某月的天数.
运行代码:
import java.util.Scanner;
public class MonthDays {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份:");
int year = sc.nextInt();
System.out.println("请输入月份:");
int month = sc.nextInt();
int days = 0;
if (month<1||month>12) {
System.out.println("输入月份有误!");
return;
}
switch (month) {
case 2: days = (year%4==0 && year%100!=0 || year%400==0)? 29:28;
break;
case 4:
case 6:
case 9:
case 11:days = 30;
break;
default:
days = 31;
}
System.out.println(year+"年"+month+"月,有"+days+"天.");
}
}
在学习了switch-case选择语句之后,我们来做一个小案列。
案例内容为电脑菜单功能——去选择菜单的功能。
按下键盘的win键弹出开始菜单。在这我们是用鼠标点击来实现选择某一项功能进行执行。那如何用Java去实现一个模拟开始菜单呢?
运行代码:
import java.util.Scanner;
public class _3_7_Windows {
public static void main(String[] args) {
System.out.println("欢迎使用Win键功能........");
System.out.println("1.计算机");
System.out.println("2.QQ");
System.out.println("3.画图");
System.out.println("4.投影仪");
System.out.println("5.关机");
System.out.println("请选择您要的操作,输入数字序号即可:");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
switch (i) {
case 1:
System.out.println("您执行了计算机的功能!");
break;
case 2:
System.out.println("您执行了QQ的功能!");
break;
case 3:
System.out.println("您执行了画图的功能!");
break;
case 4:
System.out.println("您执行了投影仪的功能!");
break;
case 5:
System.out.println("您执行了关机的功能!");
break;
default:
System.out.println("您输入有误!请重新输入!");
break;
}
}
}