开发者

How to use a value outside for loop

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 p开发者_Python百科lace 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


if(d==varArray[i])

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

or d is a variable?


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;
    }
}


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;
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜