在 if 语句中检查多个字符串的最佳方法

问题描述 投票:0回答:8

在 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)
}

但是看起来很糟糕

顺便说一句,我不会一遍又一遍地检查法国的仍然原型代码,因此我没有先检查是否有更好的方法而进入每个欧元国家。

java string if-statement
8个回答
5
投票

1。正则表达式

if (usercountry.matches("FRA|GER|ITA"))
{
    costpermile = costpermile*1.42; 
}

2。将国家/地区添加到数据结构(集合)并检查

Set<String> eurocountries= new HashSet<String>();
eurocountries.add("FRA");eurocountries.add("GER");eurocountries.add("ITA");

if (eurocountries.contains(usercountry))
{
    costpermile = costpermile*1.42; 
}

注意:我认为这是您正在寻找的正则表达式方法


1
投票

如果您使用的是 Java 7 或更高版本,您可以像这样在字符串上使用 switch 语句

switch(userCountry)
{
    case "FRA":
        costpermile = costpermile*1.42;
        break;
    default:
        break;
}

然后您可以添加您需要的任何其他案例。


1
投票

您可以将字符串存储在数组中,然后像这样迭代它:

String[] str = {"EN", "FRA", "GER"};
for (String s : str) {
    if (usercountry.equals(s)) {
        // Match: do something...
    }
}

1
投票

正如其他人所建议的,您可以使用

Set
来存储国家/地区代码:

private static final Set<String> EURO_COUNTRIES 
    = new HashSet<>(Arrays.asList("FRA", "ESP", "ITA", "GER" /*etc..*/));

然后在您的代码中,您可以通过以下方式检查国家/地区:

String userCountry = Locale.getDefault().getISO3Country();

if (EURO_COUNTRIES.contains(userCountry)) {
    // do something
}

但是,更好的长期解决方案可能是创建丰富的

enum
,特别是如果您需要为这些国家/地区代码附加更多逻辑。


0
投票

你可以这样做:

String euroCountries []  = {"FRA", "DEU", ...}

public boolean isEuroCountry(String userCountry){
  for(String country : euroCountries){
    if(usercountry.equals(country)){
         return true;
    }
  }
  return false;
}

0
投票

您可以为属于特定大陆的每个国家/地区添加前缀,然后只需检查该令牌即可。 例如在欧洲国家:

  • E_FRA
  • E_BEL
  • E_GER
  • ...

将是E

亚洲国家:

  • A_CHN
  • A_MLY
  • A_PHL
  • ...

将是A,依此类推。

if ( userCountry.startsWith("E") ) {
     // Europe countries
} else
if ( userCountry.startsWith("A") ) {
    // Asian countries
}
...

0
投票
String countries[] = {"FRA", "GER", "ENG"} // declaration of the countries you want to list.

// function to calculate the cost per mile 
public double calculateCostPerMile(String userCountry){
    double costPerMile;
    for(String country: countries){
        if(country.equals(userCountry)){
            return costPerMile*1.42; // return value

        }

    }
}

0
投票

也可以使用

org.apache.commons.lang3.StringUtils.containsAny(CharSequence cs, CharSequence... searchCharSequences)

© www.soinside.com 2019 - 2024. All rights reserved.