如果语句内部为循环Java

时间:2015-04-14 04:30:45

标签: java

我想知道我的逻辑出错了。我想在找到== true时完成for循环,如果没有找到则执行其他条件我想执行该条件。任何帮助将不胜感激..

boolean found = false;

for (String keyword : keywords) {
    found = true;
    if (input.contains(keyword)) {
        parseFile(keyword);
        break;
    }
    if (!found) {
        Writer();
        break;
    }
}

4 个答案:

答案 0 :(得分:3)

我不完全确定这是否正确,但听起来你想要遍历关键字,如果找到关键字,你想要运行你的第一个条件并离开for循环。然后,如果没有关键字匹配,则您希望执行最终条件。如果是这样,这应该符合您的要求:

boolean found = false;
for (String keyword : keywords) 
{
    if (input.contains(keyword)) 
    {
        found = true;
        parseFile(keyword);
        break;
    }
}
if (!found) 
{
    Writer();
}

答案 1 :(得分:2)

我非常确定您要根据循环中的found测试更改if。像,

// found = true;
if (input.contains(keyword)) {
    found = true; // <-- otherwise it doesn't make sense.

,然后再测试

if (!found) { // <-- can only evaluate to true if found is false.

另外,我认为这应该是在你循环之后。像,

for (String keyword : keywords) {
    if (input.contains(keyword)) {
        found = true;
        parseFile(keyword);
        break;
    }
}
if (!found) {
    Writer();
}

答案 2 :(得分:1)

您在第一个found = true语句之外设置if,因此您永远不会进入if (!found)块。相反,您可能希望将其设置为:

boolean found = false;
for (String keyword : keywords) {
    if (input.contains(keyword)) {
        found = true;
        parseFile(keyword);
        break;
    } 
}

if (!found) {
    Writer(); 
}

答案 3 :(得分:0)

通过在found = true;语句之外设置if,您可以删除found false found的任何机会。

换句话说,您已将true设置为found并且在代码中没有任何地方创建false切换到true的条件,因此它会保持if (!found)这会使整个found块无用。

您需要在for循环

之外将class TestClass { protected int j; protected BigInteger bigInt2; public void testFunction () { for (j = 1, bigInt2 = new BigInteger ("1"); j < 1000000; j++, bigInt2 = bigInt2.add (bigIntBase)) { // Do stuff } } } 设置为true
相关问题