gpt4 book ai didi

java - 对对象数组进行排序时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:18:57 25 4
gpt4 key购买 nike

问题如下:编写一个名为 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”接口(interface),例如:

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

但是,如果您在任何排序机制的具体实现方面遇到麻烦,这将无济于事。

关于java - 对对象数组进行排序时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27409802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com