IAmTheWalrus
IAmTheWalrus

Reputation: 23

Why does a semicolon after a for statement cause a compile error?

For my Java class, we are asked to add a semicolon to a working for statement and explain why the output is what it is. I don't understand why adding the semicolon creates an erroneous tree type error resulting in the code being unable to compile. Below the code is the output; I have also added backslashes to the any tag because it wasn't displaying otherwise. So, why does a semicolon after a for statement cause such an error? Thanks in advance.

package fordemo;

import java.util.Scanner;

public class ForDemo {
    public static void main(String[] args) {
        {
            Scanner user_input = new Scanner(System.in);
            System.out.println("Input a number:");
            int number = user_input.nextInt();
            for (int n = 1; n <= number; n += 2) ;
            System.out.print(n + " ");
        }
    }
}

run:

Input a number:

9

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - 
Erroneous tree type: <\any>\

at fordemo.ForDemo.main(ForDemo.java:35)

Java Result: 1

BUILD SUCCESSFUL (total time: 1 second)

Upvotes: 1

Views: 4581

Answers (4)

Wundwin Born
Wundwin Born

Reputation: 3475

When you terminate for loop with ;, it equavilent to

for (int n = 1; n <= number; n+=2 ) {
     //do nothing
}
//here n is out of variable scope
System.out.print(n + " ");}

In fact, for loop should be

for (int n = 1; n <= number; n+=2 ) {
     System.out.print(n + " ");
}

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

Your for loop don't have a body

for (int n = 1; n <= number; n+=2 ); // execute and exit and nothing do

Then you call System.out.print(n + " ");, n is not visible here. Since you are call it from outside the scope of that variable

You can use as following

for (int n = 1; n <= number; n+=2 ) {
  System.out.print(n + " ");
} 

Upvotes: 0

Chris Martin
Chris Martin

Reputation: 30746

I reformatted your code (whitespace changes only) to make it readable.

package fordemo;

import java.util.Scanner;

public class ForDemo {

    public static void main(String[] args) {

        /* Question 2 */
        {
            Scanner user_input = new Scanner(System.in);
            System.out.println("Input a number:");
            int number = user_input.nextInt();
            for (int n = 1; n <= number; n+=2 );
            System.out.print(n + " ");
        }
    }
}

The problem should be apparent now.

n is not in scope.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347314

You're teminating the for-loop with a ;...for (int n = 1; n <= number; n += 2); <--- See ; here, this means that the loop does nothing and then n becomes undefined, is it's defined only within the context of the for-loop itself...

Try something more like...

for (int n = 1; n <= number; n+=2 ) {
    System.out.print(n + " ");
}

Upvotes: 2

Related Questions