我想打印输出: 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();
}
}
答案 0 :(得分:1)
首先,不需要第二个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
循环中处理。
答案 1 :(得分:1)
问题是您正在执行count++
以及count=count+2
,因此您将打印一次奇数和一次偶数
更新
解决问题的最快方法是更改为while循环
int count = 1;
while( count <= (MAX_ODD - 2)) {
//rest of your code in loop
}
此外,您只需要一次打印
答案 2 :(得分:0)
我在您的代码中看到了许多问题:
而是在for语句中将其更新为;
for ( int count = 1; count <= (MAX_ODD - 2); count+=2)
并删除该行
count = count + 2;
检查count <= MAX_ODD
您希望循环中有一个print语句。删除该行;
//打印最后一个奇数
是System.out.print(计数);
AS @Roy Dictus建议,更改writeOdds方法以接受max_odd参数。
答案 3 :(得分:0)
第一个问题是您要两次更新计数器。
其次,随叫随到,你如何精确MAX_ODD,因为它是一个静态变量。试试这个;
public class BadNews {
public static void writeOdds(int MAX_ODD) {
// print each odd number
for ( int count = 1; count <= MAX_ODD; count+=2) {
System.out.print(count + " ");
// print the last odd number
System.out.print(count);
}
}
public static void main(String[] args) {
// write all odds up to 21
writeOdds(21); <-- Pass the MAX_ODD by parameter
// now, write all odds up to 11
writeOdds(11);
}
}
答案 4 :(得分:0)
他们不希望您使用参数化方法,而是希望您使用final int加上单独的循环来将赔率打印到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); count+=2) {
System.out.print(count + " ");
}
// print the last odd number
}
public static void main(String[] args) {
// write all odds up to 21
writeOdds();
System.out.println();
// now, write all odds up to 11
for (int count = 1; count <= 11; count+=2) {
System.out.print(count + " ");
}
}
}
答案 5 :(得分:-1)
public class BadNews {
public static final int MAX_ODD = 21;
public static void main(String[] args) {
for (int count = 1; count <= MAX_ODD; count+=2) {
System.out.print(count + " ");
}
System.out.println();
for (int count = 1; count <=(MAX_ODD-10); count+=2) {
System.out.print(count + " ");
}
}
}