0

While loop, Being Choosy,

Can someone give me a Hint on this one? number = read.next.Int(); while(number>1){ number--; if(number%3==0||number%10==3) System.out.println(number); Output 13 12 9 6 3 Expected Output 3 6 9 12 13 I've tried number++ instead of number-- but the statement isn't returning to the while condition to end.

6th Aug 2021, 9:40 PM
Dan Coble
Dan Coble - avatar
3 Réponses
+ 2
The first problem is that it's, of course, backwards. You should use "number" as the condition to test for, ie: number = read.nextInt(); int count = 0; while(count < number){ if(count % 3 == 0 || count % 10 == 3) System.out.println(count); count++; } Though to be honest, unless the question is specifically asking for a while loop implementation, a for loop is more appropriate here. For example: for(int count = 0; count < number; count++) if(count % 3 == 0 || count % 10 == 3) System.out.println(count); Since while loops are generally used when the number of iterations is NOT known, whereas for loops are for when the number of iterations ARE known. Not that it really matters, but that's the convention. Besides that, it just looks neater.
6th Aug 2021, 11:27 PM
BootInk
BootInk - avatar
0
Okay, I got it. I moved on to the next challenge which is for loops so the second part of your answer helps too because I was trying to combine a for loop with an if statement. Thanks for the help.
9th Aug 2021, 10:37 PM
Dan Coble
Dan Coble - avatar