为什么for语句后的分号会导致编译错误? [英] Why does a semicolon after a for statement cause a compile error?
问题描述
对于我的Java类,要求我们在工作中的for语句中添加分号,并说明输出为何如此.我不明白为什么添加分号会导致错误的树类型错误,从而导致代码无法编译.代码下面是输出;我还向任何标记添加了反斜杠,因为它没有显示其他方式.那么,为什么在for语句后的分号会导致这种错误?预先感谢.
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 + " ");
}
}
}
运行:
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)
推荐答案
您正在使用;
... for (int n = 1; n <= number; n += 2);
<-终止for-loop
,在这里请参见;
循环不执行任何操作,然后n
变为未定义,是因为它仅在for-loop
本身的上下文中定义...
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...
尝试类似...
for (int n = 1; n <= number; n+=2 ) {
System.out.print(n + " ");
}
这篇关于为什么for语句后的分号会导致编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!