[英]How about my understanding of my first java lab in the introduction of java programming?Is my code correct or not?
// Create a method called displayHighScorePosition
// it should a players name as a parameter, and the 2nd parameter as a position in the high score table
// You should display the player's name along with a message like " managed to get into position " and the
// position they got and a further message " on the high score table".
//
// Create a 2nd method called calculateHighScorePosition
// it should be sent one argument only, the player score
// it should return an in
// the return data should be
// 1 if the score is >=1000
// 2 if the score is >=500 and < 1000
// 3 if the score is >=100 and < 500
// 4 in all other cases
// call both methods and display the results of the following
// a score of 1500, 900, 400 and 50
public class Challenge {
public static void main(String[] args) {
int position=calculateHighScorePosition(1500);
displayHighScorePosition("Stone",position);
position=calculateHighScorePosition(900);
displayHighScorePosition("shawn",position);
position=calculateHighScorePosition(400);
displayHighScorePosition("Simon",position);
position=calculateHighScorePosition(50);
displayHighScorePosition("sks",position); }
public static void displayHighScorePosition(String playerName, int position) {
System.out.println(playerName + " managed to get into position");
System.out.println(position + " on the high score table");
}
public static int calculateHighScorePosition(int playerScore) {
if(playerScore>1000){
return 1;
}else if(playerScore>500&&playerScore<1000) {
return 2;
}else if(playerScore>100&&playerScore<500) {
return 3;
}else {
return 4;
}
}
}
編輯后,基本程序似乎還可以,但需注意以下幾點:
返回數據應該是
如果得分> = 1000,則為1
如果得分> = 500且<1000,則為2
如果分數> = 100且<500,則為3
其他所有情況為4
但是當前測試省略了測試的=
部分。 例如,嘗試運行一個分數等於500的測試用例。結果是什么?
因此,檢查可能應該類似於以下內容,將=
和來自@JohnyMopp的注釋並入並不需要&&
之外的部分:
if(playerScore >= 1000){
return 1;
} else if (playerScore >= 500) {
return 2;
} else if (playerScore >= 100) {
return 3;
} else {
return 4;
}
在邊界處編寫一些測試用例是確保程序邏輯正確運行的最佳方法。 因此,除了指定的結果外,還要在1000、500、100、499、99處添加一些測試。基本上,開始考慮可能會影響結果的極端情況。
此處有一些標准輸出示例: https : //ideone.com/sGi48C
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.