有没有办法让我可以对 ArrayList 输出进行排序,找到找到的最大数字和找到的最小数字?我现在的方式是一个“购物 list ”,其设置如下:
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());
}
}
最佳答案
您可能想要Collections.max()
(分别是Collections.min()
)。如果您希望整个列表按顺序排列,您可能需要 Collections.sort()
。
关于Java - 遍历数组列表并输出从最高到最低的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5981693/