Java中的Switch用法
阿新 • • 發佈:2019-02-17
1,在java中switch後的表示式的型別只能為以下幾種:byte、short、char、int(在Java1.6中是這樣), 在java1.7後支援了對string的判斷
public class TestSwitch{ public static void main(String args[]){ char c = 'a'; //char型別字元 switch(c){ default: System.out.println("列印預設值");break; case 'a': System.out.println("a"); break; case 'b': System.out.println('b'); break; case 'c': System.out.println('c'); break; case 'd': System.out.println("d"); break; } } }
2,在java中如果switch的case語句中少寫了break;這個關鍵字,在編譯的時候並沒有報錯,但是在執行的時候會一直執行所有case條件下的語句並不是去判斷,所以會一直執行直到遇到break關鍵字跳出
- package sampleTest;
- publicclass TestSwitch {
- publicstaticvoid main(String[] args) {
- int count = 0;
-
switch
- case0:
- System.out.println("case0");
- case1:
- System.out.println("case1");
- case2:
- System.out.println("case2");
- break;
- case3:
- System.out.println("case3");
- default:
- System.out.println("default!");
- }
- System.out.println("-------------------");
- String msg = "dragon";
- switch (msg) {
- case"rabbit":
- System.out.println("rabbit ");
- case"dragon":
- System.out.println("happy new year");
- default:
- System.out.println("what ?");
- case"monkey":
- System.out.println("monkey");
- break;
- case"tiger":
- System.out.println("tiger!!");
- }
- }
- }
輸出如下:
case0
case1
case2
-------------------
happy new year
what ?
monkey
上面例子說明了兩個問題,第一個是不加break的後果,第二個是default的位置對執行的影響
3,多個case輸出相同,可以只寫一個case,如下面這個輸出月份的天數的經典問題
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace A_Month_Has_Days_Modified
- {
- class Program
- {
- staticvoid Main(string[] args)
- {
- Console.WriteLine("請輸入你要查詢的年份");
- int year = Convert.ToInt32(Console.ReadLine());
- Console.WriteLine("請輸入你要查詢的月份");
- int month = Convert.ToInt32(Console.ReadLine());
- int bigDay = 31, smallDay = 30, leapDay = 29, nonleapDay = 28;
- bool isLeapYear;
- if ((year % 400 == 0) || ((year % 4 != 0) && (year % 100 == 0)))
- {
- isLeapYear = true;
- }
- else
- {
- isLeapYear = false;
- }
- switch (month)
- {
- case 1:
- case 3:
- case 5:
- case 7:
- case 8:
- case 10:
- case 12:
- Console.WriteLine("{0}年{1}月共有{2}天", year, month, bigDay);
- break;
- case 4:
- case 6:
- case 9:
- case 11:
- Console.WriteLine("{0}年{1}月共有{2}天", year, month, smallDay);
- break;
- case 2:
- if (isLeapYear == true)
- {
- Console.WriteLine("{0}年{1}月共有{2}天", year, month, leapDay);
- }
- else
- {
- Console.WriteLine("{0}年{1}月共有{2}天", year, month, nonleapDay);
- }
- break;
- default:
- Console.WriteLine("您輸入的年份或月份格式不正確,年份為四位數字,月份為1至12");
- break;
- }
- Console.ReadKey();
- }
- }
- }