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循环不工作
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
