【发布时间】:2020-04-23 10:27:42
【问题描述】:
我目前正在解决“练习”问题,但我被困在这个问题上: “假设您正在尝试编写一个使用循环产生以下输出的程序。下面的程序是一个解决方案的尝试,但它至少包含四个主要错误。识别并修复它们。 1 3 5 7 9 11 13 15 17 19 21 1 3 5 7 9 11 "
public class BadNews {
public static final int MAX_ODD = 21;
public static void writeOdds() {
// print each odd number
for (int count = 1; count <= (MAX_ODD - 2); count++) {
System.out.print(count + " ");
count = count + 2;
}
// print the last odd number
System.out.print(count + 2);
}
public static void main(String[] args) {
// write all odds up to 21
writeOdds();
// now, write all odds up to 11
MAX_ODD = 11;
writeOdds();
}
}
我已将代码更改为:
public class BadNews {
public static final int MAX_ODD = 21;
public static void writeOdds() {
// print each odd number
for (int count = 1; count <= (MAX_ODD); count++) {
System.out.print(count + " ");
count = count +1; //tried to chacge count++ into count + 2 but it was a miss
}
}
public static void main(String[] args) {
// write all odds up to 21
writeOdds();
// now, write all odds up to 11
MAX_ODD = 11;
writeOdds();
}
}
我认为最后一个问题是最终的 int MAX_ODD 应该移动到 main 并更改为“正常”变量(int MAX_ODD),但它以问题失败结束并注释“您的解决方案必须有一个类常量。一个常量必须是在类中的任何方法之外声明为“public static final”。” 任何想法如何解决这个问题?
【问题讨论】:
-
我测试了你自己的代码,你只需要从 MAX_ODD 中删除“final”。然后它会按照您的预期运行,并打印您想要的内容。