Jack Pettersson
Jack Pettersson

Reputation: 1666

Passing down symbol from a for loop to an if statement

It seems that a symbol in a "for loop" is local to the loop itself. Is there any way to pass the information about what the symbol is currently representing down to, for example, an if statement?

For example, this generates an error:

int[] myAry = {1, 2, 3};
for (int i : myAry)
  if (i == 2);
    System.out.println(i);

While this doesn't:

int[] myAry = {1, 2, 3};
for (int i : myAry)
  if (i == 2);
    System.out.println("Match found!");

Upvotes: 0

Views: 58

Answers (3)

Eran
Eran

Reputation: 393846

Both code snippets are wrong, and should be :

if (i == 2)
    System.out.println(i);

and

if (i == 2)
    System.out.println("Match found!");

There shouldn't be a semi colon after the condition.

The first snippet results in a compilation error since System.out.println(i); is outside the loop, so i is undefined.

The second snippet doesn't cause a compilation error (since it doesn't attempt to access i), but it is executed regardless of the result of the evaluation of the if condition, since it is outside the for loop.

Upvotes: 4

Stultuske
Stultuske

Reputation: 9437

Your first code is basically:

int[] myAry = {1, 2, 3};
for (int i : myAry){
  if (i == 2){}
}
    System.out.println(i);

So, indeed, i doesn't exist in the scope where you try to print it. Either declare i outside of the for loop, or place your brackets the way you need them to be.

Upvotes: 1

thepace
thepace

Reputation: 2221

Some ways:

  • Ensure single executable block after for if you wish to use no braces.

    int[] myAry = {1, 2, 3};
    for (int i : myAry)
      if (i == 2) // Remove the semi-colon. Seems inadvertently added.
          System.out.println(i);
    
  • Use braces.

    int[] myAry = {1, 2, 3};
    for (int i : myAry){
      if (i == 2); // Assuming this was purposeful, seems unlikely though.
          System.out.println(i);
    }
    

Upvotes: 2

Related Questions