java 更改 if else 以切换字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4780813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing if else to switch for string
提问by Sowmya
How can I write the following method using switch case
instead of if else
如何使用switch case
而不是编写以下方法if else
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
currentElement = true;
if (localName.equals("maintag"))
{
/** Start */
sitesList = new SitesList();
} else if (localName.equals("website")) {
/** Get attribute value */
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}
}
回答by Jigar Joshi
回答by Sean Patrick Floyd
Switch using Strings
使用字符串切换
You can't. Java 1.6 doesn't support switch statements with Strings.
你不能。Java 1.6 不支持带有字符串的 switch 语句。
Java 1.7 possibly will (it is one of the features of Project Coin), but for 1.6 you should either use an enum (best choice) or otherwise use a map.
Java 1.7 可能会(它是Project Coin的功能之一),但对于 1.6,您应该使用枚举(最佳选择)或以其他方式使用地图。
Pseudo-switch using a Map
使用 Map 进行伪切换
Here's how:
就是这样:
Create an interface:
创建接口:
interface SiteListProvider{
SitesList provide();
}
Now create a Map that maps Strings to different implementations of SiteListProvider
:
现在创建一个映射字符串到不同实现的映射SiteListProvider
:
Map<String, SiteListProvider> providers =
new HashMap<String, SiteListProvider>();
providers.put("foo", new SiteListProvider(){
public SitesList provide(){
return new SiteList("foo", "bar", "baz");
}
});
providers.put("phleem", new SiteListProvider(){
public SitesList provide(){
return new SiteList("otherstuff");
}
});
And now use it like this:
现在像这样使用它:
SiteList siteList = providers.get(localName).provide();
回答by sarnold
switch
in most languges, java included, only works with datatypes that are integers at heart: http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
switch
在大多数语言中,包括 java,仅适用于本质上是整数的数据类型:http: //download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You can't use switch with strings. Sorry.
您不能将 switch 与字符串一起使用。对不起。
回答by Peter Lawrey
In Java 7 you will be able to use strings, for now youc an use an enum like this.
在 Java 7 中,您将能够使用字符串,现在您可以使用这样的枚举。
enum LocalName {
maintag, website, UNKNOWN;
public static LocalName lookup(String text) {
try {
return valueOf(text);
} catch(Exception e) {
return UNKNOWN;
}
}
}
switch(LocalName.lookup(localName)) {
case maintag:
/** Start */
sitesList = new SitesList();
break;
case website:
/** Get attribute value */
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
break;
}
回答by Armando Marques Sobrinho
I solve this problem by changing the "switch" for "if" anything like this:
我通过更改“if”的“switch”来解决这个问题:
if (mystring.equals("string")
thisstring="vi";
回答by T.J. Crowder
回答by Macarse
You can't avoid the if else
since:
你无法避免,if else
因为:
A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ).
开关适用于 byte、short、char 和 int 原始数据类型。它还适用于枚举类型(在类和继承中讨论)和一些“包装”某些原始类型的特殊类:字符、字节、短整数和整数(在简单数据对象中讨论)。
From: http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
来自:http: //download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
回答by Werner van Mook
If you know what the possible answers are you could do something like:
如果您知道可能的答案是什么,您可以执行以下操作:
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
currentElement = true
switch(localName.charAt(0)) {
case 'm':
sitesList = new SitesList();
break;
case 'w':
String attr = attributes.getValue("category");
// etc.
break;
default:
break;
}
...
}
This only works if you know the expected values and they all need to have a different first character! This solution will not earn a beauty price but is AN answer to your question ;-)
这仅在您知道预期值并且它们都需要具有不同的第一个字符时才有效!此解决方案不会赚取美容价格,但可以回答您的问题;-)
回答by maaartinus
If you can replace the String by an enum, do it - as already said. If you can't, you can get the enum for String like follows:
如果您可以用枚举替换字符串,请执行此操作 - 如前所述。如果不能,您可以获取 String 的枚举,如下所示:
Declaration and initialization
声明和初始化
enum LocalName {MAINTAG, WEBSITE}
private final static Map<String, LocalName> localNameForString
= new HashMap<String, LocalName>();
static {
for (LocalName n : LocalName.values()) {
localNameForString.put(n.name().toLowerCase(), n);
}
}
Usage
用法
LocalName n = localNameForString.get(localName);
if (n==null) {
// do something
} else switch (n) {
...
}
It's a bit verbose, but not really bad, and working with enums is a pleasure. :D
这有点冗长,但还不错,与枚举一起工作是一种乐趣。:D