Java开关基础知识

问题描述:

嗨有可能在switch语句中使用字符串或需要数字值。例如,Java开关基础知识

Switch (legs){case "Nice:" return "A nice person"} 

这是可执行代码吗?

+2

你有没有尝试过了,看看会发生什么? – 2014-10-01 00:30:52

+0

[为什么我不能打开字符串?]的可能重复(http://*.com/questions/338206/why-cant-i-switch-on-a-string) – univerio 2014-10-01 01:12:04

是的。在Java 7及更高版本中,但是你的语法有点不合适。事情是这样的,

String legs = "Nice:"; 
switch (legs) { 
case "Nice:": 
    System.out.println("A nice person"); 
    break; 
default: 
    System.out.println("Not a nice person"); 
    break; 
} 

输出是

A nice person