모두 다음 if 문을 switch 문으로 변환하려고했습니다.if-else 문을 switch 문으로 변환하려고했지만 오류로 끝나는 경우
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;
}
내가 이것을 실행하려고, 일식 "의 경우 표현식은 상수 식이어야합니다"고 각각의 경우 조건에 대해 나에게 오류를 제공합니다
/**
* 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.
}
이
내 시도였다. 이 문제를 극복하는 방법을 모르겠습니다. 누구든지 나를 도울 수 있습니까? 감사.switch
문에서
case
에서
'사례 표현식은 상수 표현식이어야합니다. '여기 스위치 케이스는 사용할 수 없습니다. 모두 – Danh