What is the problem with this code? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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?

23rd May 2021, 1:35 AM
Anna Gundareva
3 Antworten
+ 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
23rd May 2021, 1:52 AM
visph
visph - avatar
+ 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); } }
23rd May 2021, 1:53 AM
visph
visph - avatar
+ 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.
23rd May 2021, 1:55 AM
Roopesh
Roopesh - avatar