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.
Aucun commentaire:
Enregistrer un commentaire