Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put a return statement inside a switch statement?

Am I allowed to have a switch statement which decides what to return? For example, I want to return something different based on what my random generator come up with. Eclipse is giving me an error wanting me to put the return statement outside the switch.

My code:

public String wordBank() { //Error here saying: "This method must return a type of string"
    String[] wordsShapes = new String[10];
    wordsShapes[1] = "square";
    wordsShapes[2] = "circle";
    wordsShapes[3] = "cone";
    wordsShapes[4] = "prisim";
    wordsShapes[5] = "cube";
    wordsShapes[6] = "cylinder";
    wordsShapes[7] = "triangle";
    wordsShapes[8] = "star";
    wordsShapes[9] = "moon";
    wordsShapes[10] = "paralellogram";

    Random rand = new Random();
    int i = rand.nextInt(11);

    if (i == 0) {
        i = rand.nextInt(11);
    }

    switch (i) {
    case 1:
        return wordsShapes[1].toString();
    case 2:
        return wordsShapes[2].toString();
    case 3:
        return wordsShapes[3].toString();
    case 4:
        return wordsShapes[4].toString();
    case 5:
        return wordsShapes[5].toString();
    case 6:
        return wordsShapes[6].toString();
    case 7:
        return wordsShapes[7].toString();
    case 8:
        return wordsShapes[8].toString();
    case 9:
        return wordsShapes[9].toString();
    case 10:
        return wordsShapes[10].toString();
    }
}
like image 457
Fouroh3 Avatar asked Jul 31 '13 03:07

Fouroh3


1 Answers

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,

like image 143
Ramon Araujo Avatar answered Oct 28 '22 16:10

Ramon Araujo