问题
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