JAVA if,switch多分支选择结构

来源:互联网 发布:distinct unique sql 编辑:程序博客网 时间:2024/06/06 00:29
if(布尔表达式1) {
语句块1;
} else if(布尔表达式2) {
语句块2;
}………
else if(布尔表达式n){
语句块n;
} else {
语句块n+1;
}
逐条if语句进行判断
条件匹配,进入语句体
否则对
if语句继续匹配
如下所示
用if判断一个一到100的随机分数,并打出如果小于60不及格
等于60及格,大于60小于等于70良,大于70小于等于80优大于80小于

等于100很优秀。

package sxt;public class Test {public static void main(String[] args) {// 随机一个1~100的数int fraction = (int) (101 * Math.random());// 输出System.out.print("李白" + fraction + "分");// 如果分数小于60输出不及格if (fraction < 60) {System.out.println("不及格");}// 分数等于60输出及格else if (fraction == 60) {System.out.println("及格");}// 大于60小于等于70else if (fraction > 60 && fraction <= 70) {System.out.println("良");}// 大于70小于等于80else if (fraction > 70 && fraction <= 80) {System.out.println("优");}// 大于80小于等于100else {System.out.println("很优秀");}}}
switch (表达式)  {
case 值1 : 
语句序列;
[break];
case 值2:
 语句序列;
[break] ;
     … … …      … …
[default:
 默认语句 ;]

事例如下:
输入月份输出对应的天数

package sxt;import java.util.Scanner;public class TestDemo {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("输出月份");int month = sc.nextInt();switch (month) {// 如果月份满足其中一项输出31天,没有break,case有穿透效果case 1:case 3:case 5:case 7:case 8:case 10:case 12:System.out.println("31天");break;// 如果月份满足其中一项输出31天,没有break,case有穿透效果case 4:case 6:case 9:case 11:System.out.println("30天");break;// 如果不满足上面就输出28天default:System.out.println("28天");break;}}}


原创粉丝点击