编写一种方法以返回出现在列表中最频繁的玩具,以及编写一种通过计数对玩具进行排序的方法。

这是我的代码

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];


我的代码有什么问题?我该怎么做?

最佳答案

问题出在您的getMostFrequentToy()方法中:

更换

        if (toyList.get(i).getCount() > maximum)
            maximum = toyList.get(i).getCount();
        position = i;




        if (toyList.get(i).getCount() > maximum) {
            maximum = toyList.get(i).getCount();
            position = i;
        }


因为您想获得对应于该最大值的位置。

09-27 02:15