繁体   English   中英

如何在 Java 中包含和比较字符串和数组

[英]How to contain and compare string and array in Java

如果比较'searchedValue'和arrayParameter,我正在使用数组和for循环。

这是我的代码:

String[] arrayParameter = new String[] {
            "math",
            "physical",
            "literary"
};

boolean found = false;

String searchedValue = "math";
String searchedValue1 = "physical";
String searchedValue2 = "literary";

for(int i=0 ; i< arrayParameter.length; i++) {

    if(arrayParameter[i].equals(searchedValue)) {
        found = true;
        break;
    }
    else if(arrayParameter[i].equals(searchedValue1)) {

        found = true;
        break;
    }
    else if(arrayParameter[i].equals(searchedValue2)) {
        found = true;
        break;
    }
}

HttpEntity<String> entity = new HttpEntity<String>(arrayParameter[i],headers);
String result = restTemplate.postForObject(url, entity, String.class);

logger.debug(result);

当我运行我的代码时,它无法比较并返回正确的结果。 如何比较/包含“searchedValue”与“arrayParameter[i]”以及何时找到字符串程序将停止并继续到方法之外?

  • 您在 for 循环之外使用“i”,它超出了它的 scope。
  • 你写了太多的 if-else 语句
boolean found = false;
String foundValue = null;

String searchedValue = "math";
String searchedValue1 = "physical";
String searchedValue2 = "literary";

for(int i=0 ; i< arrayParameter.length; i++) {

if(arrayParameter[i].contains(searchedValue) ||  arrayParameter[i].contains(searchedValue1) || arrayParameter[i].contains(searchedValue2)) {
    found = true;
    foundValue = arrayParameter[i];
    break;
}

}
HttpEntity<String> entity = new HttpEntity<String>(foundValue,headers);
String result = restTemplate.postForObject(url, entity, String.class);

logger.debug(result);

Suggestion:

您可以使用 HashSet 代替 String[] 数组。 它将减少您的搜索时间。

O(1) 搜索:


HashSet<String> setParameter = new HashSet<String>(); 

setParameter.add("math");
setParameter.add("physical");
setParameter.add("literary"); 

if(setParameter.contains(searchedValue) ||  setParameter.contains(searchedValue1) || setParameter.contains(searchedValue2)) {
    found = true;
    foundValue = arrayParameter[i];
    break;
}

我认为您可以轻松地使用Arrays.asList(arrayParameter).contains(searchedValue)来创建您的意图方法。 有了这个,你可以消除循环。 请注意,如果您使用以下方法,如果没有匹配项,则不会调用您的 API。 但是在上面的示例 API 调用即使没有匹配项也会进行, null用于foundValue。

if (Arrays.asList(arrayParameter).contains(searchedValue)){
    callApi(searchedValue)
}
if (Arrays.asList(arrayParameter).contains(searchedValue1)){
    callApi(searchedValue1)
}
if (Arrays.asList(arrayParameter).contains(searchedValue2)){
    callApi(searchedValue2)
}

private void callApi(String foundValue){
   
    HttpEntity<String> entity = new HttpEntity<String>(foundValue,headers);
    String result = restTemplate.postForObject(url, entity, String.class);
    logger.debug(result);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM