初学者在这里尝试返回评论方法:
public static String comment(int score, int parForHole) {
if (parForHole - score > 4)
return "condor!!!!";
if (parForHole - score == 3)
return "albatross!!!";
if (parForHole - score == 2)
return "eagle!!";
if (parForHole - score == 1)
return "birdie!";
if (parForHole - score == 0)
return "par";
if (parForHole - score == -1)
return "bogey";
if (parForHole - score == -2)
return "double bogey";
if (parForHole - score < -2)
return "triple+ bogey";
return "asdasd"; // Replace by a suitable switch stmt.
}
使用switch语句有类似的方法吗?我对它不太熟悉。 感谢任何帮助!
答案 0 :(得分:1)
您可以计算parForHole总分 - 得分,然后通过switch语句运行结果。
public static String comment(int score, int parForHole) {
int total = parForHole - score;
switch(total) {
case 3 :
return "albatross!!!";
// ... and so on
}
if (total > 4)
return "condor!!!!";
if (total <= 3)
return "triple+ bogey!!!!";
return "asdasd";
}
但是对于比较&gt; 4等我猜你必须保留if语句。
答案 1 :(得分:0)
public static String comment(int score, int parForHole) {
String strig;
switch(parForHole - score){
case 1:
string = "something";
break;
case 2:
string = "something else";
break;
default:
string = "default string";
break;
}
return string;
}
Switch只是基本上切换到你给它的情况。如果parForHole - 得分为1,它将切换到案例1.如果parForHole - 得分给出未定义的值,则切换将使用默认情况。