分支結構
2、switch語句
因為if語句的級聯式最多只會處理三種情況,如果出現多情況
1>可以繼續使用if語句的級聯式,但是可能代碼的可讀性就會變差。
2>采用switch語句來解決。
switch語法格式:
switch (存在多種情況的變量) {case 值1:語句(一定要包含break)case 值2:語句(一定要包含break)...default:語句(一定要包含break) }
1:變量的數據類型:byte short int char String Enum枚舉不常用
2:default的作用:所有case情況如果都不匹配,走default
3:case中break的作用:跳出switch語句的標識符
4:如果沒有break,代碼會貫穿,直到遇到break,才會跳出switch語句
練習:A~D等級判定
System.out.println("請輸入一個等級(A~D):"); Scanner scanner = new Scanner (System.in); char level = scanner.next().charAt(0); switch (level) {case 'A':System.out.println("優秀");break;case 'B':System.out.println("良好");break;case 'C':System.out.println("及格");break;case 'D':System.out.println("不及格");break;default:break; }
注:如果多個case執行的代碼一致,可以多個case合起來一起寫!!!
練習:輸入一個年份和月份,判斷這一年是平年還是閏年,并判斷這一月有多少天
System.out.println("請輸入一個年份和一個月份,中間用空格隔開:");Scanner scanner = new Scanner (System.in);int year = scanner.nextInt();if (year % 400 == 0 || (year % 4 ==0 && year % 100 !=0)) {System.out.println(year + "是閏年");} else {System.out.println(year + "是平年");}int month = scanner.nextInt();switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:System.out.println(31 + "天");break;case 4:case 6:case 9:case 11:System.out.println(30 + "天");break;case 2: if (year % 400 == 0 || (year % 4 ==0 && year % 100 !=0)) {System.out.println(29 + "天");} else {System.out.println(28 + "天");} break;default:break;}scanner.close();