我是 Java 新手,我試圖在這個類中宣告另一種方法,稱為getItemPrice,該方法將專案陣列作為輸入并以最低價格回傳專案(也考慮折扣)。
到目前為止,我已經在 main 方法中宣告了一個包含 2 個專案物件的陣列。
這是我的主要方法:
public static void main(String[] args) {
Item[] Item;
Item = new Item[2]
Item[0] = new Item(1, "Item One", 5, 2);
Item[1] = new Item(2, "Item Two", 10, 5);
}
正如您在上面看到的,每個專案陣列都有一個 id、名稱、價格和折扣。
現在,使用這些專案陣列,我試圖在這個類中宣告另一個名為 的方法,該方法getItemPrice將專案陣列作為輸入并回傳價格最低的專案(也考慮折扣)。
例如,該方法將同時接收專案一和專案 2,但將回傳專案 1,因為 5 減 2 給出 3,這小于專案 2,即 10 減 5,給出 5。
因此,專案 1 將被退回,因為它在添加折扣時價格最低。
我真的不確定如何做到這一點,所以任何幫助將不勝感激。
類實作:
public class Item {
int ItemId;
String itemName;
double itemPrice;
double itemDiscount;
public Item(int ItemId, String itemName, double itemPrice, double itemDiscount) {
super();
this.ItemId = itemId;
this.ItemName = itemName;
this.itemPrice = itemPrice;
this.itemDiscount = itemDiscount;
}
// Getters and setters follow after this
}
uj5u.com熱心網友回復:
你可以對每一個進行迭代Item,如果當前的價格低于前一個較低的價格,則保存對當前價格的參考
static Item getItemPrice(Item[] items) {
double lowerPrice = Double.MAX_VALUE;
Item lower = null;
for (Item item : items) {
double finalPrice = item.itemPrice - item.itemDiscount;
if (finalPrice < lowerPrice) {
lowerPrice = finalPrice;
lower = item;
}
}
return lower;
}
public static void main(String[] args) {
Item[] items = new Item[]{
new Item(1, "Item One", 5, 2),
new Item(2, "Item Two", 10, 5)};
System.out.println(getItemPrice(items)); // Item{id=1, name='Item One', price=5, discount=2}
}
高級水平 Stream
static Item getItemPrice(Item[] items) {
return Arrays.stream(items)
.min(Comparator.comparingDouble(item -> item.itemPrice - item.itemDiscount))
.orElse(null);
}
請注意,變數名的約定是小寫的,并且不要以類名作為前綴,一個好的類應該是
class Item {
int id;
String name;
double price;
double discount;
public Item(int id, String name, double price, double discount) {
this.id = id;
this.name = name;
this.price = price;
this.discount = discount;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/356489.html
下一篇:從建構式中提取物件值
