java for loop not working(java for循环不工作)
问题描述
我希望这不是一个愚蠢的问题,但我已经查找了我能找到的每个示例,但似乎我的代码仍然正确,但它仍然无法正常工作......我输入一个数字,它继续前进到下一行代码而不是循环.我正在使用它来填充用户输入数字的数组.感谢您的帮助,谢谢.
I hope this isn't a stupid question but I have looked up every example I can find and it still seems like I have this code right and it still isn't working... I enter one number and it moves on to the next line of code instead of looping. I'm using this to fill an array with user input numbers. I appreciate any help, thanks.
for(i=0; i<9; i++);
{
System.out.println ("Please enter a number:");
Num[i] = keyboard.nextDouble();
Sum += Num[i];
Product *= Num[i];
}
推荐答案
for 循环末尾的 ; 被当作一个空语句,相当于你的 for- 的一个空块环形.编译器将您的代码读取为:
The ; at the end of the for loop is taken as an empty statement, the equivalent of an empty block for your for-loop. The compiler is reading your code as:
int i;
....
for(i=0; i<9; i++)
/* no-op */;
/* inline block with no relation to for-loop */
{
System.out.println ("Please enter a number:");
Num[i] = keyboard.nextDouble();
Sum += Num[i];
Product *= Num[i];
}
删除 ; 以获得您的预期行为.
Remove the ; to get your intended behavior.
如果您不需要循环外的 i,您可以将其声明移到 for 语句中.
If you don't need the i outside of the loop, you could move its declaration within the for statement.
for(int i=0; i<9; i++)
{
// `i` is only usable here now
}
// `i` is now out of scope and not usable
在错误的分号 ; 存在时使用此语法会产生一个编译错误,该错误会在之前提醒您注意错误的 ;.编译器会看到:
Using this syntax when the erroneous semicolon ; was present would have produced a compile error that would alerted you to the erroneous ; earlier. THe compiler would see this:
for(int i=0; i<9; i++)
/* no-op */;
/* inline block with no relation to for-loop */
{
System.out.println ("Please enter a number:");
Num[i] = keyboard.nextDouble(); // compile error now - `i` is out-of-scope
Sum += Num[i];
Product *= Num[i];
}
这将是一个示例,说明在可能的情况下限制变量的范围是一种很好的做法.
This would be an example why it is good practice to limit the scope of variables when possible.
这篇关于java for循环不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java for循环不工作
基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
