为什么for语句后的分号会导致编译错误?

编程入门 行业动态 更新时间:2024-10-18 22:36:59
本文介绍了为什么for语句后的分号会导致编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于我的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语句后的分号会导致编译错误?

本文发布于:2023-11-09 20:58:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分号   语句   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!