问题如下:
编写一个名为SortSalon的程序,该程序包含一个数组,该数组可容纳六个HairSalon对象并用数据填充它。包括一种按服务价格升序对数组进行排序的方法。调用该方法并显示结果。

public class SortSalon
{
    private static HairSalon [] itsArray = new HairSalon[6];

    public SortSalon()
    {
        itsArray[0] = new HairSalon("cut", 10.50, 15);
        itsArray[1] = new HairSalon("shampoo", 5.00, 10);
        itsArray[2] = new HairSalon("manicure", 20.00, 20);
        itsArray[3] = new HairSalon("cut", 10.50, 15);
        itsArray[4] = new HairSalon("manicure", 20.00, 20);
        itsArray[5] = new HairSalon("manicure", 20.00, 20);
    }

    public HairSalon [] sortByPrice(HairSalon [] par)
    {
        HairSalon [] newArray = new HairSalon[6];
        int x = 0;
        int y = 0;
        HairSalon smallest = itsArray[1];

        for(int i = 0; i < itsArray.length; i++)
        {
            while(y < itsArray.length - 1)
            {
                if(itsArray[y].getPrice() == smallest.getPrice())
                {
                    smallest = itsArray[y];
                    newArray[x] = smallest;
                }
                else
                {
                    //smallest = itsArray[y];
                    for(int c = 0; c < itsArray.length - 1; c++)
                    {
                        if(itsArray[y].getPrice() < itsArray[y + 1].getPrice()
                        && itsArray[y].getPrice() >  smallest.getPrice())
                        {
                            smallest = itsArray[y];
                            newArray[x] = smallest;
                        }
                    }
                }
                y++;
            }
            y = 0;
            //newArray[x] = smallest;
            x++;
        }

        int z = 0;
        System.out.println("Ascending order: ");

        while(z < newArray.length)
        {
            System.out.println(newArray[z].toString());
            z++;
        }
        return newArray;
    }

    public static void main()
    {
        SortSalon test = new SortSalon();
        test.sortByPrice(itsArray);
    }
}


无法获得按价格正确排序对象的方法。任何建议将不胜感激!

最佳答案

我认为最好的方法(使用已经定义的排序算法是使用接口“ Comparable”,例如:

private class HairSalon implements Comparable<HairSalon>{
    public String type = null;
    public double price = 0;
    public float number = 0;

    public HairSalon(String type,double price,float number){
        this.type = type;
        this.price = price;
        this.number = number;
    }

    @Override
    public int compareTo(HairSalon compa) {
        int ret = 0;
        if(this.price < compa.price) ret = -1;

        if(this.price > compa.price){
            ret = 1;
        }else{ret = 0;}

        return ret;
    }


}

然后,您可以使用Collections排序算法:

Collections.sort(new ArrayList<HairSalon>(Arrays.asList(itsArray)));


但是,您在使用任何排序机制的特定实现时都遇到了麻烦,这无济于事。

10-07 19:23
查看更多