我的while循环中的语法错误很简单

时间:2014-01-03 23:45:45

标签: java while-loop infinite-loop

您正在为考试做一些修改并找到过去的问题。

写一个while循环来打印0到10之间的奇数。 我一直在玩弄谷歌并尝试谷歌,但它的这么简单,令我困惑。我知道它在某处有一个简单的语法错误。

我试过移动x ++,尝试移动print语句,只是没有得到它。请有人照亮这个。我通常会使用for循环,因为它会更容易,但问题是要求while循环。

public class OddNumbersWhile {
    public static void main (String[]args){
        int x = 0;
        while (x <10){
            if (x % 2 !=0) {
                x++;
        System.out.println(x);
}} }}

4 个答案:

答案 0 :(得分:1)

你应该把你的大括号放在不同的行上。

这就是问题所在:你在if语句中递增x,因此一旦if语句无法触发就会导致无限循环,因为你的while条件无法达到。

这可能更接近你所追求的。

public class OddNumbersWhile {
    public static void main (String[]args){
        int x = 0;
        while (x <10){
            if (x % 2 !=0) {
                System.out.println(x);
            }
            x++;
        }
    }
}

答案 1 :(得分:0)

试试这个

public class OddNumbersWhile {
    public static void main (String[]args){
        int x = 0;
        while (x < 10){
            if (x % 2 != 0) {
                System.out.println(x);
            }
            x++;
        }
    }
}

答案 2 :(得分:0)

你定义x = 0,当while循环开始时,你说:

if (x % 2 !=0)

但是x%2是= 0,因为x是0,所以x ++永远不会运行。

P.S。

好的,N0ir给了你代码。我试图用逻辑把你带到解决方案。

答案 3 :(得分:0)

您应该将x++移到if语句之外。

public class OddNumbersWhile {
public static void main (String[]args){
    int x = 0;
    while (x <10){
        if (x % 2 !=0) {
            System.out.println(x);
        }
        x++;
    }
  }
}