+ 1

While loops exercise

Problem A client wants you to write a program that prints all numbers from 0 to the inputted number that are either a multiplier of 3 or end with 3. My approach import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); int number = read.nextInt(); //your code goes here while (number > 0) { if (number % 10 ==3 || number%3 == 0){ System.out.println(number); } number --; } } } I need to reverse the order of which the number printed My output : 13 12 9 6 3 Expected output 3 6 9 12 13

10th Jan 2021, 8:55 AM
Didi
10 ответов
+ 6
10th Jan 2021, 9:13 AM
P∆WAN M∆URY∆
P∆WAN M∆URY∆ - avatar
+ 3
Melissa Rommelman As number-- is within the if statement, it is changed only if the condition is true (not on each iteration of the loop!) Plus your code "counts down" to 0. To solve the task the output must be in ascending order. (Also see the code example that someone posted in this thread)
16th Apr 2021, 2:06 PM
Lisa
Lisa - avatar
+ 2
Your output is reversed because the while goes backwards (down from number to 0). You could rewrite it by using an additional counter variable and then count upwards
10th Jan 2021, 9:08 AM
Lisa
Lisa - avatar
+ 2
something like int counter = 0; while(counter < number) { ... counter++; }
10th Jan 2021, 9:11 AM
Lisa
Lisa - avatar
+ 1
how can i do that can you give me a hint ?
10th Jan 2021, 9:09 AM
Didi
+ 1
Thank you guys
10th Jan 2021, 9:15 AM
Didi
+ 1
I didn't think about the if for that reason I wanna thank you. The next code has the right output= import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); int number = read.nextInt(); //your code goes here int num = 1; while (num <= number) { if (num % 10 ==3 || num %3 == 0){ System.out.println(num); } num++; } } }
25th Aug 2021, 9:10 PM
Liliana Catherine Díaz Arango
Liliana Catherine Díaz Arango - avatar
0
I have worked on this problem for 4 hours and I know don't understand what I am doing wrong import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); int number = read.nextInt(); //your code goes here while(number>0){ if(number%3==0 || number%10==3){ { System .out.println(number); number--; } } }
16th Apr 2021, 1:27 PM
Melissa Rommelman
Melissa Rommelman - avatar
0
Lisa I have tried all the ways listed (copy and paste). I either get an error for } on line xx or timed out still don't understand what I am doing wrong
16th Apr 2021, 3:01 PM
Melissa Rommelman
Melissa Rommelman - avatar
0
Melissa Rommelman This sounds like there could be some bracket missing or another syntax error... Can you link your code? (Copy&Paste to a script, save as java, make public and link here)
16th Apr 2021, 3:26 PM
Lisa
Lisa - avatar