Dan Dan - 1 month ago 12
Java Question

Trying to convert an if-else statement to a switch statement but ending up with an error

all I've been trying to convert the following if statement into a switch statement.

/**
* Return appropriate comment for given score and par for hole.
* You can assume that score is not less than 4 below par for hole.
* For example, if score is 4 below par, return "condor!!!!",
* if score is 3 below par, return "albatross!!!",
* if score is 2 below par, return "eagle!!", etc.
* See Assign 2 description for full list of comments.
* @param score
* @param parForHole
* @return appropriate comment for given score and par for hole.
*/
public static String comment(int score, int parForHole) {
if ( score == parForHole-4)
return "condor!!!!";
if ( score == parForHole-3)
return "albatross!!!";
if ( score == parForHole-2)
return "eagle!!";
if ( score == parForHole-1)
return "birdie!";
if ( score == parForHole)
return "par";
if ( score == parForHole+1)
return "bogey";
if ( score == parForHole+2)
return "double bogey";
if ( score == parForHole+3)
return "triple bogey";

return "Not valid"; // Replace by a suitable switch stmt.
}


This was my attempt:

public static String comment(int score, int parForHole) {

String monthString;
switch (score) {
case parForHole-4: monthString = "condor!!!!";
break;
case parForHole-3: monthString = "albatross!!!";
break;
case parForHole-2: monthString = "eagle!!";
break;
case parForHole-1: monthString = "birdie!";
break;
case parForHole: monthString = "par";
break;
case parForHole+1: monthString = "bogey";
break;
case parForHole+2: monthString = "double bogey";
break;
case parForHole+3: monthString = "triple bogey";
break;
default: monthString = "Invalid";
break;
}
return monthString;

}


When I try to run this, eclipse gives me errors for each case condition that "case expressions must be constant expressions". I am not sure how to overcome this problem. Can anyone help me out? Thanks.

Answer

As Eclipse is trying to tell you, this is not possible in Java. You can only use constant expressions in case statements, and that doesn't fit well in your situation.

Anyway, neither if-else nor switch are great here. It would be better to use a table-based solution, for example:

static String[] comments = {
    "condor!!!!",
    "albatross!!!",
    "eagle!!",
    "birdie!",
    "par",
    "bogey",
    "double bogey",
    "triple bogey"
};

public static String comment(int score, int parForHole) {
    int index = score - parForHole + 4;
    if (index < 0 || index >= comments.length) {
        return "Not valid";
    }
    return comments[index];
}