-1
我有一個購物清單,其中包含一定數量的項目。通過用戶輸入,我想詢問用戶他們想要添加到他們的購物袋中的多少相同的物品。如何將重複值添加到ArrayList
例如:我有以下ArrayList newProduct = {"apple","orange","banana"};
。現在我想要提示用戶選擇newProduct中的哪些項目(以及多少項)是否希望添加到名爲bag
的第二個數組中。如果用戶選擇數量爲2的蘋果,則2個蘋果將被添加到bag
,並且看起來像這樣bag = {"apple","apple"};
我試圖使用會重複該值的操作。但它不太好。這有什麼問題?
import java.util.*;
import java.util.stream.IntStream;
public class Bag extends Price {
static Scanner input = new Scanner(System.in);
@SuppressWarnings("unused")
private static String newName;
private int choice;
public ArrayList<String> bag = new ArrayList<String>();
public List<Double> bagPrice = new ArrayList<Double>();
public void addProduct() {
Bag item = new Bag();
while (sum(bagPrice) <= 58.00) {
System.out.println("Choose a Priority");
item.choice = input.nextInt();
System.out.println("Choose Quantity");
int quantity = input.nextInt();
if (IntStream.of(newPriority).anyMatch(x -> x == item.choice)) {
item.bag.add(newProduct.get(item.choice));
System.out.print("PRICE $ " + Double.valueOf(formatter.format(price.get(item.choice - 1))));
bagPrice.add(price.get(item.choice - 1));
System.out.println("BAG: " + item.bag);
System.out.println("TOTAL : " + Double.valueOf(formatter.format(sum(bagPrice))));
} else {
System.out.println("Priority Does Not Exist");
}
}
}
public double sum(List<Double> bagPrice) {
double sum = 0.00;
for (double s : bagPrice) {
sum = sum + s;
}
return sum;
}
}
我是相當新的編程,所以如果有任何更好的建議,我將不勝感激。
除非這是一個任務,一個更好的建立也只是使用'Map'使用的產品名稱爲關鍵和數量作爲價值。 – Carcigenicate
這是不是很清楚你在這裏問什麼。你能告訴我們你的完整代碼嗎?特別是定義了'Bag','sum()'和'newPriority'。 –
它看起來像一個任務。但我相信誰給了你這個練習並不意味着你認爲他的意思。仔細閱讀你的指示,然後使用HashMap。 –
auval