What is the problem with this code? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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 Respostas
+ 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