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

I am doing some java exercises, and I am trying to make a method that totals up to 100 and prints the number every time the loop cycle 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 will return String. However, the error says that I am not returning a value. I know that I have to make it return String outside the for loop, but I have some problems figuring out how I should return the return value. I also know that I can use arrays or even an arrayList to fix this problem, but I think it is possible without this, and I would like to try to do it.

Any help would be greatly 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){
    }
}
+4
3

, . , , . , for , .

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");
    }
  }
}

, void, .

+7

, for.

, , for, , "Fizz!".

+2

, . , , .

private static String fizz ="Fizz!";
private static String buzz ="Buzz!";    

public static void main(String[] args){
    for (int number = 0; number < 100; number++){
        String word = checkNumber(number);
        System.out.println(word);
    }
}

private static String checkNumber(int number){
    String value = "";
    if (number%3 == 0){
        value += fizz;
    }
    if (number%5 == 0){
        value += buzz;
    }
    if (value.isEmpty()) {
        value = String.valueOf(number);
    }
    return value;
}

:

  • private . .

  • ( ). , . , .

  • if / else if / else if / if / if. 15 3 5.

+1

All Articles