Ste*_*eve 7 java iteration syntax for-loop
我希望这不是一个愚蠢的问题,但我查找了我能找到的每一个例子,看起来我仍然没有这个代码,但它仍然无法工作......我输入一个数字,然后继续下一个代码行而不是循环.我正在使用它来填充用户输入数字的数组.我感谢任何帮助,谢谢.
for(i=0; i<9; i++);
{
System.out.println ("Please enter a number:");
Num[i] = keyboard.nextDouble();
Sum += Num[i];
Product *= Num[i];
}
Run Code Online (Sandbox Code Playgroud)
Ber*_*t F 17
将;在该月底循环被取空语句,空块,为您的for循环的等价物.编译器正在读取您的代码:
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];
}
Run Code Online (Sandbox Code Playgroud)
删除;以获得您的预期行为.
如果您不需要i循环外部,则可以在for语句中移动其声明.
for(int i=0; i<9; i++)
{
// `i` is only usable here now
}
// `i` is now out of scope and not usable
Run Code Online (Sandbox Code Playgroud)
当存在错误的分号时使用此语法;会产生编译错误,该错误会提醒您错误的;早期错误.编译器会看到这个:
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];
}
Run Code Online (Sandbox Code Playgroud)
这将是一个例子,为什么在可能的情况下限制变量范围是一种好的做法.