我想打印输出: 1 3 5 7 9 11 13 15 17 19 21 1 3 5 7 9 11 但我得到这个输出: 1 34 67 910 1213 1516 1819 211 34 67 910 1213 1516 1819 21
有人可以解释一下我在逻辑上犯的错误吗?
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);
}
}
public static void main(String[] args) {
// write all odds up to 21
writeOdds();
// now, write all odds up to 11
writeOdds();
}
}
最佳答案
首先,不需要第二个System.out.print
。
其次,我看到您达到了 21,但是您在代码中的何处指定第二次调用应该达到 11?
您可以通过将上限设置为 writeOdds
函数的参数来实现此目的:
public static void writeOdds(int upperLimit)
{
for(int count = 1; count <= upperLimit; count += 2)
...
然后您可以调用它两次,即 writeOdds(21)
和 writeOdds(11)
。
哦,还有,您可以取出 count = count + 2
,这是在 for
循环中处理的。
关于java - 不明白代码逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19997886/