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: \
at fordemo.ForDemo.main(ForDemo.java:35)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
解决方案
You're teminating the for-loop with a ;...for (int n = 1; n <= number; n += 2);
Try something more like...
for (int n = 1; n <= number; n+=2 ) {
System.out.print(n + " ");
}