问题描述:

Hi doing some revising for an exam and came upon this past question.

Write a while loop to print the odd numbers between 0 and 10.

I've been toying about and trying to Google but its such a simple thing and its confusing me. I know its a simple syntax error somewhere.

I have tried moving the x++ about, tried moving the print statement about, just not getting it. can somebody shine light on this please. I would normally use a for loop as it would be easier but the question asks for a while loop.

public class OddNumbersWhile {

public static void main (String[]args){

int x = 0;

while (x <10){

if (x % 2 !=0) {

x++;

System.out.println(x);

}} }}

网友答案:

You should put your closing braces on separate lines.

And here's the problem: You're incrementing x in your if-statement thus resulting in an infinite loop once the if-statement fails to trigger since your while condition cannot be reached.

This is probably closer to what you're after.

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

try this

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

you define x = 0, when the while loop begins, you say:

if (x % 2 !=0)

but x % 2 is = 0, because x is 0, so x++ will never run.

P.S.

Ok, N0ir gave you the code. I was trying to bring you to the solution using logic.

网友答案:

You should move x++ outside of the if statement.

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