2017-07-25 38 views
0

我有一個學校項目,我應該使用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

'Arrays.toString()'? – dehasi

+2

創建一個POJO和一個該類型的數組 - 然後對該數組進行排序。或者,每次交換'costPerDay' **也**交換'carModel'。 –

回答

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]); 
} 
+0

非常感謝!我在這樣一件容易的事情上打破了我的頭!只是在最後一部分,它不應該是'carModel.length-1',而是'carModel.length'只有 –

+0

你是對的,我糾正了它。 – Garlic

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

現在像我這裏有costPerDay[order[x]]可以打印使用carModel[order[i]]