+ 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
10 Antworten
+ 6
Hi Didi,
🙂 this will help you.🐾
https://code.sololearn.com/caBWEXS4iSU9/?ref=app
+ 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)
+ 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
+ 2
something like
int counter = 0;
while(counter < number) {
...
counter++;
}
+ 1
how can i do that can you give me a hint ?
+ 1
Thank you guys
+ 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++;
}
}
}
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--;
}
}
}
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
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)