1. 程式人生 > >switch是否能作用在byte 上,是否能作用在long 上,是否能作用在String上?

switch是否能作用在byte 上,是否能作用在long 上,是否能作用在String上?

switch可作用於char byte short int
switch可作用於char byte short int對應的包裝類
switch不可作用於long double float boolean,包括他們的包裝類
 
public class Test {
	public static void main(String[] args) {
		// switch可作用於char byte short int
		char season1 = 3;
		byte season2 = 3;
		short season3 = 3;
		int season4 = 3;
// switch可作用於char byte short int對應的包裝類 Character season11 = 3; Byte season22 = 3; Short season33 = 3; Integer season44 = 3; // 下面的基本型別的包裝類就不行了,還有double float的包裝類 // Long season = 0; // switch不可作用於long double float boolean,包括他們的包裝類 long season5 = 3; double season6 = 3; float season7 =
3f; boolean season8 = false; //...... String strSeason = ""; switch (season1) { case 1: strSeason = "Spring"; break; case 2: strSeason = "Summer"; break; case 3: strSeason = "Fall"; break; case 4: strSeason = "Winter"; break; default: strSeason = "四季中沒有這個季節"
; break; } System.out.println("strSeason:" + strSeason); } }
switch中可以是字串型別String
public class Test {
	public static void main(String[] args) {
		int season = 0;
		String strSeason = "Summer";
		switch (strSeason.toLowerCase()) {
		case "spring":
			season = 1;
			break;
		case "summer":
			season = 2;
			break;
		case "fall":
			season = 3;
			break;
		case "winter":
			season = 4;
			break;
		default:
			season = -1;// 沒找到對應的季節
			break;
		}
		System.out.println(strSeason + "-->" + season);
	}
}