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循环不工作
基础教程推荐
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01