问题如下: 编写一个名为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);
}
}
无法通过价格正确对对象进行排序。任何建议将不胜感激!
答案 0 :(得分:0)
使用Comparator
对HairSalon对象进行排序,您可以定义自定义比较方式,并使用Arrays.sort(T[] a, Comparator<? super T> c)
进行排序
您可以选择Comparable
或Comparator
进行排序。我更喜欢使用Comparator
,原因是比较逻辑在一个单独的类中。这意味着你不需要修改你的HairSalon
类,你可以有多个自定义的Comparators类用于不同的字段比较/排序。
样品:
public class HairSalon {
private final String type;
private final double price;
public HairSalon(String type, double price){
this.type = type;
this.price = price;
}
public String getType(){ return this.type;}
public double getPrice(){return this.price;}
}
public class PriceComparator implements Comparator<HairSalon> {
/**
*comparison/sorting logic is here
*/
@Override
public int compare(HairSalon hs1, HairSalon hs2)
{
if(hs1.getPrice() > hs2.getPrice()){return 1;}
else if(hs1.getPrice() == hs2.getPrice()){return 0;}
else{return -1;}
}
}
如何排序:
//if you put all your HairSalon objects in an array:
Arrays.sort(hairSalonsArray, new PriceComparator())
//if you put all your HairSalon in a list
Collections.sort(hairSalonsList, new PriceComparator());
答案 1 :(得分:0)
我认为最好的方法(使用已经定义的排序算法使用界面&#34;可比较&#34;,例如:
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.sort(new ArrayList<HairSalon>(Arrays.asList(itsArray)));
但是你在使用任何排序机制的具体实现方面遇到了麻烦,这对你来说无济于事。