请帮助我学习程序
我需要修改addPlayer函数以按排序顺序插入数组中的每个数字。程序应输出:-100 -45 4 19 50 55等提示:---〉重载add()方法对于维护排序顺序的列表特别有用〈------
前4步输出正常,然后不工作(((
import java.util.ArrayList;
import java.util.Scanner;
public class Array_sort_by_add {
// Adds playerNum to end of ArrayList
public static void addPlayer (ArrayList<Integer> players, int playerNum) {
int i = 1;
boolean foundHigher = false;
// Look for first item greater than playerNum
foundHigher = false;
i = 1;
while ( (!foundHigher) && (i < players.size()) ) {
if (players.get(i) > playerNum) {
// FIXME: insert playerNum at element i
players.add(i, playerNum); // is it connect?
foundHigher = true;
}
++i;
}
// FIXME: change so executes if higher number NOT found
if (true) { // No higher number found, add at end
players.add(new Integer(playerNum));
// It should be something here - don't know what (((
}
return;
}
// Prints player numbers currently in ArrayList
public static void printPlayers(ArrayList<Integer> players) {
// int i = 1;
for (int i = 1; i < players.size(); ++i) {
System.out.println(" " + i + ". " + players.get(i));
}
return;
}
// Maintains ArrayList of player numbers
public static void main (String [] args) {
ArrayList<Integer> players = new ArrayList<Integer>();
// adding 10 values
addPlayer(players, 55);
addPlayer(players, 4);
addPlayer(players, 33);
addPlayer(players, 30);
addPlayer(players, 40);
addPlayer(players, 80);
addPlayer(players, 70);
addPlayer(players, 19);
addPlayer(players, -45);
addPlayer(players, -100);
printPlayers(players);
return;
}
}
5条答案
按热度按时间mm5n2pyu1#
我读了你的代码,我建议你使用
compareTo()
方法来比较每个整数。Java文档
而且你需要改变这个循环的开始索引,因为否则你会跳过第一项。
ykejflvf2#
这就是你们班要找的东西:
lymgl2op3#
我发现了一个更简单的方法然后什么答案给...
gev0vcfq4#
或者只是:
bjp0bcyl5#
第一个 FIXME 很简单,您只需将“i”元素添加到playerNum中,但第二个 FIXME 可以通过两种方式应用。因为它符合逻辑,您可以使用不等式运算符: