// 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