我有一个学校项目,我应该使用 Java 在 BlueJ 中制作一个汽车租赁应用程序。对于一部分,我有 2 个数组,一个用于价格,一个用于汽车名称。我必须按价格降序打印汽车名称。我已经设法使用气泡排序按降序对价格数组进行排序,但是当我对价格数组进行排序时,我无法弄清楚如何打印汽车的名称。请帮忙。
String carModel[] = {"A", "B", "C"}; //Names of cars
int costPerDay[] = {100, 75, 250}; //Rental cost per day
for(int x = 0; x < costPerDay.length-1; x++) { //Sort the Cost Per Day Array in descending order using bubble sort
for(int j = x + 1; j < costPerDay.length; j++) {
if(costPerDay[x] < costPerDay[j]) {
int t = costPerDay[x];
costPerDay[x] = costPerDay[j];
costPerDay[j] = t;
}
}
}
这是代码片段。我需要按相应成本的降序打印汽车的名称。
提前感谢!
String carModel[] = {"A", "B", "C"}; //Names of cars
int costPerDay[] = {100, 75, 250}; //Rental cost per day
for(int x = 0; x < costPerDay.length-1; x++){ //Sort the Cost Per Day Array in descending order using bubble sort
for(int j = x + 1; j < costPerDay.length; j++){
if(costPerDay[x] < costPerDay[j]){
int t = costPerDay[x];
String s = carModel[x];
costPerDay[x] = costPerDay[j];
costPerDay[j] = t;
carModel[x] = carModel[j];
carModel[j] = s;
}
}
}
for(int x = 0; x < carModel.length; x++){
System.out.println(carModel[i]);
}
有一个技巧可以做到这一点。使用另一个指示顺序的数组。
String carModel[] = {"A", "B", "C"}; //Names of cars
int costPerDay[] = {100, 75, 250}; //Rental cost per day
// Here's the trick - use an order array.
int order[] = {0,1,2};
for(int x = 0; x < costPerDay.length-1; x++){ //Sort the Cost Per Day Array in descending order using bubble sort
for(int j = x + 1; j < costPerDay.length; j++){
if(costPerDay[order[x]] < costPerDay[order[j]]){
int t = order[x];
order[x] = order[j];
order[j] = t;
}
}
}
现在您可以使用carModel[order[i]]
打印,就像我在这里使用costPerDay[order[x]]
一样。