Yutian  Zheng
Yutian Zheng

Reputation: 21

Why does my code only execute once

I want to print all the even numbers, but it only gives me 0!!

public class DataType {

public static void main(String[] args){
    int number=0;
    int max=20;
    do{
        System.out.println("this is an even number"+ number);
        number++;
    }while(number<=max&&EvenNumber(number));

}



public static boolean EvenNumber(int a)
{
    if((a%2)==0)
    {
        return true;
    }else 
        return false;       
}


}

Upvotes: 2

Views: 82

Answers (5)

John Muiruri
John Muiruri

Reputation: 26

Because in the second iteration the loop will exit. if you want to print even numbers then the code should be

do{
    if(EvenNumber(number)) {
        System.out.println("this is an even number"+ number);
    }
    number++;
}while(number<=max );

Upvotes: 0

that is what your condition states: do while both conditions meet!, afters doing number++ for the 1st time the left side of the condition returns false and your loop is done!

you mean for sure:

    do {
        if (isEvenNumber(number)) {
            System.out.println("this is an even number" + number);
        }
        number++;
    } while (number <= max);

remember, following code means

while(number <= max && EvenNumber(number))

while BOTH conditions meet...

Upvotes: 2

Harmlezz
Harmlezz

Reputation: 8058

If you intend to find all even number between [0, 20] you may change your code to this version:

public static void main(String[] args) {
    int max=20;
    for (int number = 0; number <= max; number++) {
        if (number % 2 == 0) {
            System.out.printf("%d is an even number.\n", number);
        }
    }
}

This reads like:

  • start with number 0
  • while number not past 20
  • if number is even print it
  • continue with next number

Upvotes: 0

ElGerar
ElGerar

Reputation: 101

Because in your code, If number is equals to 1, while condition is false

Upvotes: 0

dumbPotato21
dumbPotato21

Reputation: 5695

After number++;, number becomes 1, and thus the condition becomes false, and the loop terminates.

I assume, you wanted to do

do {
    if (isEvenNumber(number)) System.out.println(number);
    number++;
} while(number<=max);

Upvotes: 0

Related Questions