2011-05-12 64 views
0

有沒有辦法讓它,所以我可以排序通過一個ArrayList輸出最高的號碼與找到的最低號碼?我有辦法,現在是一個「shoppinglist」所設置的是這樣的:Java - 通過arraylist並輸出最高到最低的數字?

public void addToBag(String anyItem, int anyUnits, double anyCost){ 
    int checkUnits = anyUnits; 
    double checkCost = anyCost; 
    if(checkUnits < 0 || checkCost < 0){ 
     System.out.println("You must enter a value equal to or greater than 0!"); 
    }else{ 
    shoppingBag.add(new Item(anyItem, anyUnits, anyCost)); 
} 
} 

和輸出僅輸出列表

public void calculateSalesReceipt(){ 
    System.out.println("Enter the sales tax percentage (ex. 0.08 for 8%) or type \"random\" for a random number: "); 
    double tax = keybd.nextDouble(); 
    if(tax < 0){ 
     System.out.println("You must enter a value equal to or greater than 0!"); 
    }else{ 
    getPricePreTax(); 
    total = total; 
    taxCost = total * tax; 
    finaltotal = total + taxCost; 
    System.out.println("Sales Receipt"); 
    System.out.println("-------------"); 
    for(Item currentProduct : shoppingBag){ 
     System.out.println(currentProduct.getName() + " - " + currentProduct.getUnits() + " units " + " - $" + currentProduct.getCost()); 
    } 
    System.out.println("Total cost: $" + total); 
    System.out.println("Total tax: $" + taxCost); 
    System.out.println("Total cost with tax: $" + finaltotal); 
    System.out.println("Do you have any coupons? Enter \"yes\" or \"no\""); 
    String answer = keybd.next(); 
    if(answer.equals("yes")){ 
       applyCoupon(); 
      }else if(answer.equals("no")){ 
      System.out.println("Thank you!"); 
     }else if(answer != "yes" || answer != "no"){ 
      System.out.println("Thank you!"); 
     } 
    System.out.println("Coupon discounts: $" + couponAmount); 
    System.out.println("Grand total: $" + (finaltotal-couponAmount)); 
} 
} 

謝謝!

編輯:

將這項工作?

public void getLargest(){ 
    for(Item currentProduct : shoppingBag){ 
     System.out.println(Collections.max()); 
    } 
} 

回答

5

你可能想Collections.max()(和Collections.min(),分別)。如果你想要整個列表,你可能想要Collections.sort()

+0

好的,你能解決這個問題嗎?我在編輯它 – tekman22 2011-05-12 17:18:47

+0

public void getLargest(){ for(Item currentProduct:shoppingBag){ System.out.println(Collections.max()); } } – tekman22 2011-05-12 17:18:59

1

使用Google Guava

Function<Item, Double> itemCostFunction = new Function<Item, Double>() { 
    @Override public Double apply(Item item) { 
    return item.getCost(); 
    } 
}; 

List<Item> sortedItems = Ordering.natural().onResultOf(itemCostFunction).sortedCopy(shoppingBag); 

現在

Item biggest = Iterables.getLast(sortedItems); // costliest 
Item smallest = sortedItems.get(0); // cheapest 
+4

...是的,這真的很不錯。但是也許正如這個傢伙正在學習的那樣,最好能夠理解如何使用標準api來做到這一點。最後一行看起來有點像魔術...... :-) – KarlP 2011-05-12 17:17:51

+0

美麗的魔法! – sjr 2011-05-12 17:18:30

+0

爲什麼不使用ordering.max/ordering.min? – Ray 2011-05-12 20:03:53

0

你要什麼排序呢?成本?

您可以創建一個新的類; CostComparator執行Comparator<Item>,並比較Item s依賴於他們的價格。