Reputation: 21
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
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
Reputation: 48258
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
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:
Upvotes: 0
Reputation: 101
Because in your code, If number is equals to 1, while condition is false
Upvotes: 0
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