我有一个学校项目,我应该使用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;
}
}
}
这是代码段。我需要按相应费用的降序打印汽车的名称。
提前致谢!
答案 0 :(得分:1)
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]);
}
答案 1 :(得分:0)
有一个技巧可以做到这一点。使用另一个指示顺序的数组。
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]]
进行打印。