【发布时间】:2016-02-26 14:29:32
【问题描述】:
我有一个字符串变量,它每次运行时都可以有不同的长度。 有了它,我检查它的开头,例如:
public void defineLocation(){
if (newLocation.substring(0,2).equals("DO") || newLocation.substring(0,2).equals("30") || newLocation.substring(0,2).equals("21")) {
locationInDc = "DOOR";
} else if (newLocation.substring(0,2).equals("VT") || newLocation.substring(0,3).equals("MUF")) {
locationInDc = "BLOUBLOU";
} else if (newLocation.substring(0,3).equals("MAH")) {
locationInDc = "BLOBLO";
} else if (newLocation.substring(0,7).equals("Zone 72") || newLocation.substring(0,7).equals("Zone 70")){
locationInDc = "BLOFBLOF";
}
我知道这不是最有效的方法,而且它肯定会中断,如果我的变量不在前 3 次检查中的任何一个中,但字符数仍然少于 7,那么它将引发错误。
有没有更“正确”的方法来做到这一点?我应该先检查字符串包含多少个字符,然后将其指向正确的检查/“ifs”吗?谢谢。
【问题讨论】:
标签: java string if-statement substring case