java 中switch

支持的类型:

在jdk1.6中,支持的类型只有 byte,short,char,int 。千万记住没有long。

但在jdk1.7之后,又可以支持string类型。


char类型:

char charA='a';
			switch (charA) {
			case 'a':
				System.out.println("输出a");
				break;
			case 'b':
				System.out.println("输出b");
				break;
			case 'c':
				System.out.println("输出c");
				break;
			default:
				System.out.println("错误!");
				break;
			}

 String类型:

	String str="abc";
		switch (str) {
		case "abc":
			System.out.println("输出abc");
			break;
		case "abs":
			System.out.println("输出abs");
			break;
		case "bcd":
			System.out.println("输出bcd");
			break;
		default:
			System.out.println("错误!");
			break;
		}

 


 

break:

如果case之后没有break语句,则会从匹配到的地方一直执行下去,直到结束,或遇到break。

	String str="abs";
		switch (str) {
		case "abc":
			System.out.println("输出abc");

		case "abs":
			System.out.println("输出abs");

		case "bcd":
			System.out.println("输出bcd");
			break;
		default:
			System.out.println("错误!");
			break;
		}

  输出:

输出abs
输出bcd

 

原文地址:https://www.cnblogs.com/xuesheng/p/7712373.html