2011-05-12 3 views
0

ArrayList 출력을 통해 찾을 수있는 가장 낮은 번호와 함께 발견 된 가장 높은 번호를 정렬 할 수있는 방법이 있습니까? 단지 목록을Java - arraylist를 거쳐 가장 높은 숫자에서 가장 낮은 숫자로 출력 하시겠습니까?

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

출력 : 내가 가지고있는 방법은 지금과 같이 설정 "shoppinglist"입니다!

편집 :

겠습니까이 작품?

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

답변

5

당신은 아마 Collections.max() (그리고 Collections.min(), 각각을) 할 수 있습니다. 전체 목록을 순서대로 원하면 Collections.sort()을 원할 것입니다.

+0

좋아, 해결할 수 있습니까? 편집 중입니다. – tekman22

+0

공백 void getLargest() { for (Item currentProduct : shoppingBag) { System.out.println (Collections.max()); } } – tekman22

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

+0

아름다운 마술! – sjr

+0

ordering.max/ordering.min을 사용하지 않는 이유는 무엇입니까? – Ray

0

당신이에 정렬 하시겠습니까? 비용?

새 클래스를 만들 수 있습니다. CostComparatorComparator<Item>이며, 가격은 Item입니다.

관련 문제