Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a for loop method with if statements return the correct "return" without array?

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){
    }
}
like image 247
user3130840 Avatar asked Feb 14 '23 07:02

user3130840


1 Answers

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.

like image 137
Hovercraft Full Of Eels Avatar answered Mar 16 '23 01:03

Hovercraft Full Of Eels