2012-09-07 132 views
0

我正在寫一個方法,返回某個標記的輸入的字符串。給它一個標記,然後確定標記適合的等級。但它給了我這個錯誤:方法不返回字符串

private String getGrade(int marks)throws Exception { ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^ 此方法必須返回一個String類型的結果

的代碼是:

String a = "A, Well done!"; 
String b = "B, still room for improvement."; 
String c = "C, need to improve a lot!"; 
String d = "D, you got lucky!"; 
String e = "You failed, please retake the test!"; 


if (marks>80 || marks==80){ 
return a; 
} else if (marks>70 && marks<80 || marks==70){ 
return b; 
}else if (marks>60 && marks<70 || marks==60){ 
return c; 
} else if (marks>=50 && marks <60){ 
return d; 
}else if (marks<50){ 
return e; 
} 

回答

0

編譯器不會嘗試聰明地評估所有可能的情況下,並確保您將始終在條件的所有分支中返回一個字符串。您還需要有一個else子句,並且沒有if,它將返回一個默認值(這是一個字符串)。

0

好像你需要一個「其他」末

0
String a = "A, Well done!"; 
String b = "B, still room for improvement."; 
String c = "C, need to improve a lot!"; 
String d = "D, you got lucky!"; 
String e = "You failed, please retake the test!"; 


if (marks>80 || marks==80){ 
return a; 
} else if (marks>70 && marks<80 || marks==70){ 
return b; 
}else if (marks>60 && marks<70 || marks==60){ 
return c; 
} else if (marks>=50 && marks <60){ 
return d; 
}else{ 
return e; 
} 

正如你沒t return a value if如果(標記< 50)`雖然我們知道這裏沒有失敗的posiblity但程序以這種方式運行語句失敗只能像我做的那樣使用

0

您必須在此輸出其他字符並返回字符串值,否則語句將不會執行。試試吧,希望它能幫助你。

0

你可以試試這可以幫助你。

String a = "A, Well done!"; 
String b = "B, still room for improvement."; 
String c = "C, need to improve a lot!"; 
String d = "D, you got lucky!"; 
String e = "You failed, please retake the test!"; 


if (marks>=80){ 
return a; 
} else if (marks>=70) { 
return b; 
} else if (marks>=60){ 
return c; 
} else if (marks>=50){ 
return d; 
} else { 
return e; 
} 

OR

String a = "A, Well done!"; 
String b = "B, still room for improvement."; 
String c = "C, need to improve a lot!"; 
String d = "D, you got lucky!"; 
String e = "You failed, please retake the test!"; 
String r="" 

if (marks>=80){ 
r=a; 
} else if (marks>=70) { 
r=b; 
} else if (marks>=60){ 
r=c; 
} else if (marks>=50){ 
r=d; 
} else { 
r=e; 
} 

return r; 

我希望第二個是好的,因爲它總是有回報的路徑和返回的東西調用者。