I am doing some java exercises and I am trying to make a method that counts to 100 and prints the number each time the for loop "loops".
The exception is that it will print "Fizz" when the number is divisible by 3 and "Buzz" when the number is divisible by 5.
Now, I have three return types in my method that is gonna return a String. However, the error says I do not return a value. I am aware that I have to make it return a String outside the for loop but I am having some trouble figuring out how I should get to return the value that I want.
I am also aware that I could use arrays or even arrayList to fix this problem but I think its possible without that and I would like to try doing so.
Any help would be very appreciated!
Here is the code:
package etcOvaningar;
public class ovning1 {
public static String fizz ="Fizz!";
public static String buzz ="Buzz!";
public static String countDown(){
for (int number = 0; number < 100; number++){
if (number%3 == 0){
return fizz;
}
else if (number%5 == 0){
return buzz;
}
else
return String.valueOf(number);
}
//I need to insert a return here I suppose, but I want the correct return from the if and else //statements
}
public static void main(String[] args){
}
}
Don't "return" in the loop, but rather print. When you return, the method exits, and the loop loops no more. If you simply print the necessary text, the for loop will continue to loop until it reaches its natural end condition.
public static void countDown(){
for (int number = 0; number < 100; number++){
if (number % (3*5) == 0) {
System.out.println("fizzbuzz");
} else
if (number % 3 == 0){
System.out.println("fizz");
} else
if (number % 5 == 0){
System.out.println("buzz");
}
}
}
Note as per Martin Dinov, this method should be declared to return void
, nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With