+ 1

Why do i keep getting an overload error every time i run this?

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){ continue; } System.out.println(number--); } } } The question is : Write a program that takes N numbers as input and outputs the numbers from N to 0, skipping the ones that are multiples of 3. I dont know how else to write this or even why there is an error. From what i understand the code says: While the number is great than or equal to 0 check if the number is a multiple of "3" by dividing the number by 3 and seeing if the remainder is 0. If the remainder is not 0 leave this statement. print out on a new line number - 1. can someone explain my error?

21st Apr 2021, 6:42 PM
Alyson Jones
3 Respuestas
+ 2
Your problem is "continue". Continue means do nothing and just go on with the loop (ignore the rest after continue). Means in your case: number % 3 gets true -> continue -> jump to the head of your loop -> check condition (is true because nothing happend to number) -> number % 3 is true -> continue and so on... Using continue inside a for loop is no problem, because normally you incrment/decrement your variable in the head of the loop. e.g. for(int i = 0; i <= 10; i++){ if(i % 3 == 0) continue; } -> continue -> head of the loop and here i gets incremented In your while loop if you want to use continue you can do this: if(number % 3 == 0){ number--; continue; }
21st Apr 2021, 7:09 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
@Denise Roßberg Thank you that makes a lot of sense.
27th Apr 2021, 3:55 AM
Alyson Jones
0
Change == with !=, put the println in the then branch and remove the else branch. Number-- goes outside the if
21st Apr 2021, 8:34 PM
Ciro Pellegrino
Ciro Pellegrino - avatar