好的,我正在使用 getSharedPreferences 来存储我的高分,但在我填满它之前,我想通过和数组将分数按升序排序,但如果它在第一个 pos 中找到小于它的分数,那么它不会检查其余的最小的?
//function to add score to array and sort it
public void addscoretoarray(int mScore){
for(int pos = 0; pos< score.length; pos++){
if(score[pos] > mScore){
//do nothing
}else {
//Add the score into that position
score[pos] = mScore;
break;
}
}
sortArray(score);
}
我应该在循环之前和之后调用 sortArray() 来解决这个问题,还是有更好的方法来实现相同的结果?
我还应该提到 sortArray(score) 函数只是调用 Arrays.sort(score) 其中 score 是 mScore 的数组
编辑:根据@Vincent Ramdhanie 发布的内容,我修改了帖子:
public void addscoretoarray(int mScore){
int pos = score.length;
//sort the array (in ascending order)
sortArray(score);
//go though the array( in descending order) and check for a place that suits the conditions
while(pos>=0 && score[pos] > mScore){
pos--; //do nothing as score[pos] is larger than mScore
}
//so once a pos is found (e.g. broke out of the while loop)
//check that it is still in the list
if(pos >= 0){
//if it is then move everything down 1 position
for(int i = 0; i < pos; i++){
score[i] = score[i+1];
}
//replace the initial pos with the new score
score[pos] = mScore;
}
}
我仍然相信它会在for(int i = 0; i < pos; i++){
循环中退出列表。