如何使用数组排序?

时间:2015-09-21 22:10:59

标签: arrays sorting selection-sort

编写一个程序,使用数组,根据价格按升序排序10个玉米饼的价格。我正在尝试排序炸玉米饼。用户必须输入10个炸玉米饼的名称和价格,然后按升序对它们进行排序。

到目前为止,我有:

public class TacoSorter {

public static void main(String[] args) {
    // TODO Auto-generated method stub

Scanner keyboard = new Scanner(System.in);

System.out.println("Welcome to the taco price sorter! Enter 10 taco names and prices and I'll sort it!");
System.out.println("Enter the name of taco ");

Scanner input = new Scanner(System.in);

final int TotalTacos = 10;

double[]tacos = new double[TotalTacos];


for(int n =0; n < tacos.length; n++){
    System.out.println("Enter a name of taco" + (n+1));

    tacos[n] = input.nextInt();

    System.out.println("Enter the price of the taco");
}
}

我希望结果有点类似 欢迎来到taco价格分拣机!输入10个炸玉米饼的名称和价格,我会对它进行排序!

Enter the name of taco 1
Crunchy Taco
Enter taco's price
1.19
Enter the name of taco 2
Crunchy Taco Supreme
Enter taco's price
1.59
Enter the name of taco 3
Soft Taco
Enter taco's price
1.19
Enter the name of taco 4
Soft Taco Supreme
Enter taco's price
1.59
Enter the name of taco 5
Chicken Soft Taco
Enter taco's price
1.79
Enter the name of taco 6
Crispy Potato Soft Taco
Enter taco's price
0.99
Enter the name of taco 7
Double Decker Taco
Enter taco's price
1.89
Enter the name of taco 8
Double Decker Taco Supreme
Enter taco's price
2.29
Enter the name of taco 9
Doritos Locos Taco (Nacho Cheese)
Enter taco's price
1.49
Enter the name of taco 10
Doritos Locs Tacos(Fiery) Supreme
Enter taco's price
1.89

分类玉米饼

Taco Prices Crispy Potato Soft Taco 0.99
Taco Prices Crunchy Taco 1.19
Taco Prices Soft Taco 1.19
Taco Prices Doritos Locos Taco (Nacho Cheese) 1.49
Taco Prices Crunchy Taco Supreme 1.59
Taco Prices Soft Taco Supreme 1.59
Taco Prices Chicken Soft Taco 1.79
Taco Prices Double Decker Taco 1.89
Taco Prices Doritos Locs Tacos(Fiery) Supreme 1.89
Taco Prices Double Decker Taco Supreme 2.29
Finally:

1 个答案:

答案 0 :(得分:0)

给定一个double值数组,让我们说

double dArr[] = {0.99, 1.19, 1.19, 1.49, 1.59, 1.59, 1.79, 1.89, 1.89, 2.29};

您可以通过说

对这些值进行排序
Arrays.sort(dArr);

作为建议,由于您的文本与每个价格值直接关联,因此您为键值配对创建了一个完美的场景。我不建议仅使用数组并按价格排序,因为现在您必须添加其他逻辑以将价格与特定价格描述相关联。出于这些原因,我建议您使用HashMap,例如。

对HashMap进行排序同样方便,只需使用Collections.sort()方法即可。干杯!