如何找到两个数组之间的字符串匹配-Java

时间:2018-09-04 08:29:22

标签: java arrays

我有两个包含一些字符串的数组,如下所示:

数组#1

abcd                    
efgh            
servicegroup_1
ijkl 

数组#2

servicegroup_3
servicegroup_1

如果数组1包含数组2的至少一个字符串,我想打印一个"VERIFY: OK"这样的字符串(在控制台上)。否则,必须打印字符串"VERIFY: KO"

我实现了如下代码:

for (int i = 0; i < scopeFile.length; i++) {
                for (String element : scopeJWT) {
                    if (scopeFile[i].contains(element)) {
                        ctx.setSendZuulResponse(true);
                        System.out.println(now + " --- " + "[Check Signature: OK]" + " [Verify Scope: OK]" + " [Verify expTime: OK]");
                    } else {
                        ctx.setSendZuulResponse(false);
                        ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                        System.err.println(now + " --- " + "[VERIFY SCOPE: KO]");
                    }
                }
}

但是,它同时返回VERIFY SCOPE: OKVERIFY SCOPE: KO,即使考虑到我报告的数组,我也只会打印VERIFY SCOPE: OK(因为数组#1包含servicegroup_1

有什么想法可以解决我的代码吗?谢谢

1 个答案:

答案 0 :(得分:2)

在Array1中找到字符串后,您忘记中断循环。 尝试在此行之后添加break;

System.out.println(now + " --- " + "[Check Signature: OK]" + " [Verify Scope: OK]" + " [Verify expTime: OK]");

并在循环外检查不正常情况。

像这样:

boolean isOk = false;
for (int i = 0; i < scopeFile.length; i++) {
    for (String element : scopeJWT) {
        if (scopeFile[i].contains(element)) {
            ctx.setSendZuulResponse(true);
            System.out.println(now + " --- " + "[Check Signature: OK]" + " [Verify Scope: OK]" + " [Verify expTime: OK]");
            isOk = true;
            break;
        }
    }
}
if (!isOk) {
    ctx.setSendZuulResponse(false);
    ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
    System.err.println(now + " --- " + "[VERIFY SCOPE: KO]");
}