我想使用的字符串switch语句,但它给编译错误。如果有人告诉我如何在switch-case语句中使用String,这对我会有所帮助。
1
A
回答
5
有一种方式,如果你真的想使用switch语句。 创建一个枚举类,其中包括switch语句的情况下
public enum MustUseSwitch{
value1,
value2,
value3;
}
然后用枚举切换到报表。
switch(MustUseSwitch.valueOf(stringVariable)){
case value1:
System.out.println("Value1!");
break;
case value2:
System.out.println("Value2!");
break;
case value3:
System.out.println("Value3!");
break;
}
+1
那么这显然与使用String-> integer中的散列表相同 - 尽管是一个巧妙的技巧。 – Voo 2011-12-18 23:12:37
3
你不能。使用if/else if/else if/else。除非你使用Java7。在这个重复的问题这个答案可以解释它远胜于我可以:https://stackoverflow.com/a/338230/3333
0
你不能在switch
语句中使用String
,但你可以使用Enum
类型。使用Enum
比使用String
甚至public static final int MY_CONSTANT
要好得多。
你会找到一个很好的教程在这里:Java Enum type tutorial
4
前面已经说过,你不能。有关技术细节,请参阅有关compiling switches的规格。使用Java SE 7,此功能已实施。有关使用开关String
与JDK 7的示例,请参阅this page。
也许this question也可能有帮助。
2
不能直接使用字符串,但你可以做出关键字符串数组,快速搜索它,打开索引,就像这样:
String[] sortedKeys = new String[] {"alpha", "bravo", "delta", "zebra"};
int keyIndex = Arrays.binarySearch(sortedKeys, switchKey);
switch(keyIndex) {
case 0: // alpha
break;
case 1: // bravo
break;
case 2: // delta
break;
case 3: // zebra
break;
}
相关问题
- 1. switch语句中的switch语句?
- 2. 作为switch语句实现的菜单
- 3. Switch语句如何工作
- 4. switch语句不工作
- 5. SWITCH语句不工作 - Java
- 6. Switch语句VS If语句
- 7. 在switch语句
- 8. switch语句
- 9. SQL switch语句
- 10. 在switch语句
- 11. JavaScript switch语句
- 12. switch语句
- 13. PHP switch语句
- 14. Golang switch语句
- 15. switch语句8
- 16. Javascript switch语句?
- 17. PowerShell Switch语句
- 18. c switch语句
- 19. switch语句
- 20. gcov和switch语句
- 21. if和switch语句
- 22. 情况/ switch语句
- 23. switch语句困难
- 24. $ _GET与switch语句
- 25. 处理switch语句
- 26. Android AlertDialog.Builder switch语句
- 27. Switch vs if语句
- 28. 错误switch语句
- 29. 创建switch语句
- 30. 这个switch语句
字符串不能在Java中的switch语句中使用。 – mowwwalker 2011-12-18 22:40:10
@Walkerneo自Java7以来并非如此。这也是建议的修复:使用最新版本。 – Voo 2011-12-18 22:42:30