个性化阅读
专注于IT技术分析

Switch语句中的字符串

本文概述

在Java 7中, Java允许你在switch语句的表达式中使用字符串对象。为了使用字符串, 你需要考虑以下几点:

它只能是字符串对象。

Object game = "Hockey"; // It is not allowed
	String game = "Hockey"; // It is OK.

字符串对象区分大小写。

"Hickey" and "hocker" are not equal.

没有空对象

传递字符串对象时要小心, 将null对象的原因传递给NullPointerException。


Switch语句示例1中的字符串

public class StringInSwitchStatementExample {
	public static void main(String[] args) {
		String game = "Cricket";
		switch(game){
		case "Hockey":
			System.out.println("Let's play Hockey");
			break;
		case "Cricket":
			System.out.println("Let's play Cricket");
			break;
		case "Football":
			System.out.println("Let's play Football");
		}
	}
}

输出:

Let's play Cricket

Switch语句示例2中的字符串

public class StringInSwitchStatementExample {
	public static void main(String[] args) {
		String game = "Card-Games";
		switch(game){
		case "Hockey": case"Cricket": case"Football":
			System.out.println("This is a outdoor game");
			break;
		case "Chess": case"Card-Games": case"Puzzles": case"Indoor basketball":
			System.out.println("This is a indoor game");
			break;
		default: 
			System.out.println("What game it is?");
		}
	}
}

输出:

This is a indoor game
赞(0)
未经允许不得转载:srcmini » Switch语句中的字符串

评论 抢沙发

评论前必须登录!