[英]How do I sort using arrays?
编写一个程序,使用数组根据价格对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");
}
}
我希望结果有点像墨西哥卷饼价格分拣机! 输入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:
给定一个双精度值数组,可以说
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()
方法即可。 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.