+ 2
What is the problem with this code?
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); int number = read.nextInt(); //Š²Š²ŠµŠ“ŠøŃŠµ ŠŗŠ¾Š“ ŃŃŠ“Š° do{ if (number % 3 == 0){ continue; } System.out.println(number); number--; } while (number > -1); } } It returns execution times out, but I donāt understand why. Can you help me please?
3 Answers
+ 3
well, when your code encounter a number divisible by 3 he never change its value, so you will never end the loop ^^
instead of == 0, use !=0 and replace 'continue' by moving here your print statement ;P
+ 3
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int number = read.nextInt();
do{
if (number % 3 != 0){
System.out.println(number);
}
number--;
} while (number > -1);
}
}
+ 3
Let's assume the number is 6 (multiple of 3)
Then
number % 3 == 0 // becomes true
And skip to next value
The next time number DIDN'T CHANGED
number is still 6 and number % 3 == 0 is still true. This creates a infinite loop.
Add number-- before 'continue' statement.