【发布时间】:2015-10-27 13:16:23
【问题描述】:
在 if 语句中检查多个字符串的最干净的方法是什么,我希望能够检查用户所在的国家/地区是否使用欧元,我将放入 ("???") 。因为这行得通。
if (usercountry.equals("FRA") || usercountry.equals("FRA")||
usercountry.equals("FRA") || usercountry.equals("FRA") ||
usercountry.equals("FRA") || usercountry.equals("FRA") ||
usercountry.equals("FRA") || usercountry.equals("FRA") ||
usercountry.equals("FRA")) {
costpermile = costpermile*1.42; //(costpermile=£) (costpermile*1.42=Euros)
}
但它看起来很糟糕
顺便说一句,我不会一遍又一遍地检查法国的原型代码,所以我进入每个欧元国家时都会先检查是否有更好的方法。
【问题讨论】:
-
你的问题有点不清楚。这:
usercountry.equals("FRA")||usercountry.equals("FRA")与usercountry.equals("FRA")相同(与自身进行或运算不会影响其值)。那么在这些 or 中的每一个中,是应该改变 variable 还是字符串文字?也就是说,你想要usercountry.equals("FRA") || usercountry.equals("BEL"),还是usercountry.equals("FRA") || somethingelse.equals("FRA")?这些是不同的答案。 -
将所有需要的匹配项放入
List并使用contains。如果List不发生变化(很大),您可以将其维护为static资源。 -
为什么不使用switch statement。只需将所有案例的正文留空,没有
break,除了最后一个匹配案例,并提供定义:-) -
Set而不是List。
标签: java string if-statement