Can I put a return statement inside a switch statement?

You can put return inside switch but you don't need to use switch in this case.


Sorry, but in that case, why not just simply do:

return wordsShapes[i].toString();

This way you can avoid the switch and all.

Hope that helps,


The problem is not that you have return statements inside the switch statement, which are perfectly fine, but you have no return after the switch statement. If your switch statement completes without returning, what will happen now?

The rules of Java require that all paths through a value-returning function encounter a return statement. In your case, even though you know the value of i will always be of a value that will cause a return from the switch, the Java compiler isn't smart enough to determine that.

(ASIDE: By the way, you didn't actually prevent the value 0 from being generated; maybe your if should be a while.)

ADDENDUM: In case you are interested, here's an implementation. See http://ideone.com/IpIwis for the live example.

import java.util.Random;
class Main {
    private static final Random random = new Random();

    private static final String[] SHAPES = {
        "square", "circle", "cone", "prism", "cube", "cylinder", "triangle",
        "star", "moon", "parallelogram"
    };

    public static String randomShapeWord() {
        return SHAPES[random.nextInt(SHAPES.length)];
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            System.out.println(randomShapeWord());
        }
    }
}

Note the best practice of having the random number generator defined outside the function.