java for循环不起作用 [英] java for loop not working
问题描述
我希望这不是一个愚蠢的问题,但是我已经查找了所有可以找到的示例,并且看起来我仍然拥有正确的代码,但是仍然无法正常工作...我输入了一个数字,然后继续操作到下一行代码,而不是循环.我正在用它来填充用户输入数字的数组.感谢您的帮助,谢谢.
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循环不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!