How to use a value outside for loop

隐身守侯 提交于 2020-02-07 06:46:04

问题


In the following code i need the value of varArray[i] for executing the if-else statements but the if-else statements are to be executed only once. If i place the if-else statements outside the for loop the if-else statements do execute correctly. When i place the if-else statement inside the for loop the if-else statements get executed multiple times.

for (int i=0;i<varArray.length;i++) 
{
    varArray[i]= rand.nextInt(1999)-1000;
    System.out.println(varArray[i]);


    if(d==varArray[i])
    {
        System.out.println(d);      
        System.out.println(i+1);
    }  
    else if(d!=varArray[i])
    { 
        System.out.println(d);
        System.out.println(0);
    }
}

Need help on this. have been searching for hours


回答1:


if(d==varArray[i])

did you mean to say if(varArray[i]=='d') ?

or d is a variable?




回答2:


you can use break; to exit the for loop when the if statement is true.

for (int i = 0; i < varArray.length; i++) {
    varArray[i] = rand.nextInt(1999) - 1000;
    System.out.println(varArray[i]);

    if (d == varArray[i]) {
        System.out.println(d);      
        System.out.println(i + 1);
        break;
    }
    else if(d != varArray[i])
    { 
        System.out.println(d);
        System.out.println(0);
        break;
    }
}



回答3:


for (int i = 0; i < varArray.length; i++)
{
    varArray[i] = rand.nextInt(1999) - 1000;
    System.out.println(varArray[i]);

    if (d == varArray[i])
    {
        System.out.println(d);      
        System.out.println(i + 1);
        break;
    }
    else if(d != varArray[i])
    { 
        System.out.println(d);
        System.out.println(0);
        break;
    }
}

When the program reaches the newly added break (in this modified snippet) it will exit out of the for loop. Therefore only executing it once.

The author has wanted to edit my answer saying:

The break statement is making the code jump out of the for loop. i want the for loop statements to execute completely but the if-else should execute only once.

To do this:

Boolean didExecuteIfElse = false; for (int i = 0; i < varArray.length; i++) { varArray[i] = rand.nextInt(1999) - 1000; System.out.println(varArray[i]);

if (didExecuteIfElse == false) {
     if (d == varArray[i])
     {
        System.out.println(d);      
        System.out.println(i + 1);
     }
     else if(d != varArray[i])
     { 
        System.out.println(d);
        System.out.println(0);
     }
     didExecuteIfElse = true;
 }
}


来源:https://stackoverflow.com/questions/5629841/how-to-use-a-value-outside-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!