我正在尝试编译
public class ForwardLoop {
public static void main(String[] args) {
int firstNumber = 5;
int lastNumber = 45;
int hopValue = 5;
for(firstNumber; firstNumber <= lastNumber; firstNumber = firstNumber + hopValue) {
System.out.print(firstNumber);
}
}
}
但我最终在第9行收到错误,声明这不是声明。
提前感谢您的帮助。
答案 0 :(得分:6)
for
循环语句中的初始化必须是有效语句。 firstNumber
不是有效的陈述。在您的情况下,您可以将初始化作为空语句,因为您已经在之前分配了初始值:
for (; firstNumber <= lastNumber; firstNumber = firstNumber + hopValue) {
System.out.print(firstNumber);
}
或者您可以在for
循环内移动声明,但这会将其范围限制为仅循环:
// You can also use the += operator
for (int firstNumber = 5; firstNumber <= lastNumber; firstNumber += hopValue) {
System.out.print(firstNumber);
}
答案 1 :(得分:0)
for loop
的语法for(initialization; condition; iteration)
{
//statements
}
正如您在代码中看到的那样,您未初始化firstNumber
,因此请使用正确的语法编写代码,如下所示:
for(firstNumber=5; firstNumber <= lastNumber; firstNumber = firstNumber + hopValue)
{
System.out.print(firstNumber );
}
仅在for循环中初始化firstNumber,或者如果在for循环之前初始化变量,则将初始化保持为空白,以便如下所示:
for( ;condition; iteration)
{
// statements
}