gpt4 book ai didi

java - 尝试将 if-else 语句转换为 switch 语句,但最终出现错误

转载 作者:行者123 更新时间:2023-12-01 07:20:20 24 4
gpt4 key购买 nike

我一直在尝试将以下 if 语句转换为 switch 语句。

/**
* 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.
}

这是我的尝试:

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;

}

当我尝试运行它时,Eclipse 会针对每个 case 条件给出错误,即“case 表达式必须是常量表达式”。我不知道如何克服这个问题。谁能帮我吗?谢谢。

最佳答案

正如 Eclipse 试图告诉您的那样,这在 Java 中是不可能的。您只能在 case 语句中使用常量表达式,这不太适合您的情况。

无论如何,if-else 和 switch 在这里都不是很好。最好使用基于表格的解决方案,例如:

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];
}

关于java - 尝试将 if-else 语句转换为 switch 语句,但最终出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40439113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com