編寫一種方法來返回列表中最常出現的玩具,另一種方法是通過計數來分類玩具。使用ArrayList對Java中最高最低的對象排序?
這是我的代碼
import java.util.ArrayList;
public class ToyStore {
private ArrayList<Toy> toyList;
public ToyStore() {
}
public void loadToys(String toys) {
toyList = new ArrayList<Toy>();
for (String item : toys.split(" ")) {
Toy t = getThatToy(item);
if (t == null) {
toyList.add(new Toy(item));
} else {
t.setCount(t.getCount() + 1);
}
}
}
public Toy getThatToy(String nm) {
for (Toy item : toyList) {
if (item.getName().equals(nm)) {
return item;
}
}
return null;
}
public String getMostFrequentToy() {
int position = 0;
int maximum = Integer.MIN_VALUE;
for (int i = toyList.size() - 1; i >= 0; i--) {
if (toyList.get(i).getCount() > maximum)
maximum = toyList.get(i).getCount();
position = i;
}
return toyList.get(position).getName();
}
public void sortToysByCount() {
ArrayList<Toy> t = new ArrayList<Toy>();
int count = 0;
int size = toyList.size();
for (int i = size; i > 0; i--) {
t.add(new Toy(getMostFrequentToy()));
t.get(count).setCount(getThatToy(getMostFrequentToy()).getCount());
toyList.remove(getThatToy(getMostFrequentToy()));
count++;
}
toyList = t;
}
public String toString() {
return toyList + "" + "\n" + "max == " + getMostFrequentToy();
}
}
這是我關心
public void sortToysByCount() {
ArrayList<Toy> t = new ArrayList<Toy>();
int count = 0;
int size = toyList.size();
for (int i = size; i > 0; i--) {
t.add(new Toy(getMostFrequentToy()));
t.get(count).setCount(getThatToy(getMostFrequentToy()).getCount());
toyList.remove(getThatToy(getMostFrequentToy()));
count++;
}
toyList = t;
}
這裏是我的輸出
[sorry 4, bat 1, train 2, teddy 2, ball 2]
這裏的方法就是我想要的
[sorry 4, train 2, teddy 2, ball 2, bat 1];
我的代碼有什麼問題?我該怎麼做?
用調試器遍歷你的代碼並找出它。家庭作業是爲了通過試驗和錯誤來教導,如果我們爲你做這件事有什麼意義? –
它看起來像一個家庭作業。這是我們的[關於作業]的政策(http://meta.programmers.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems)。 –