2016-12-13 6 views
-1

私は初心者で、各製品(例えば4コークス)の飲み物の数を返すことができるように私の確立されたarraylistにアクセスするための手がかりがありませんarraylistを使用して各製品の飲み物の数を返す方法を作成するには?

P.S.製品は私の他のクラスの名前です。私はこれが役立つかもしれないと思う

import java.util.ArrayList; 

public class VendingMachine { 

    ArrayList <Product> vending = new ArrayList <Product>(); 



public VendingMachine(int maxType, int quantity) { 

    int maxCap= maxType*quantity; 
    vending = new ArrayList <Product> (maxCap); 
} 

//Initialize the number & quantity of the products 

public ArrayList <Product> initialize() { 

    for (int i=0; i<6; i++) { 
     Product coke = new Product("Coke", 1.30, 230, 350, false); 
     vending.add(coke); 
    } 

    for (int i=0; i<6; i++) { 
     Product pepsi = new Product("Pepsi", 1.10, 240, 350, false); 
     vending.add(pepsi); 
    } 

    for (int i=0; i<6; i++) { 
     Product gingerAle = new Product("GingerAle", 1.30, 210, 320, false); 
     vending.add(gingerAle); 
    } 

    for (int i=0; i<6; i++) { 
     Product dietCoke = new Product("DietCoke", 1.50, 200, 310, true); 
     vending.add(dietCoke); 
    } 

    for (int i=0; i<6; i++) { 
     Product dietPepsi = new Product("DietPepsi", 1.40, 190, 320, true); 
     vending.add(dietPepsi); 
    } 
    return vending;  
} 
+0

私はJavaに慣れていませんが、VendingMachineクラスの一部を販売しているArrayListではありませんか?もしそうなら、VendingMachine.vendingを繰り返して、製品名の数を数えることはできませんか? forループのように各製品を通過し、いくつかのパラメータに対してproduct.nameをチェックし、それが本当であればいくつかのカウンタをインクリメントしますか? – bi0phaz3

+0

コメントありがとうございました!私はちょうどそれを試みたが、私はエラーを表示し続け、私は反復を使用させない。 – Ryelle

+0

あなたの反復コードを表示できますか? – bi0phaz3

答えて

2

はここで、これまでに私のコードです。これを試してみてください。 VendingMachineクラスのメソッドとして実装します。

public int getProductCount(String pName) throws IllegalArgumentException { 
    int count = 0; 

    if (pName == null) { 
     throw new IllegalArgumentException(); 
    } 

    for (Product item : this.vending) { 
     //Assuming the instance variable of your Product class is called name 
     //Also assuming name is private and you have a getter method in your Product class 
     if (item.getName().equalsIgnoreCase(pName)) { 
      count++; 
     } 
    } 
    return count; 
} 
+0

ありがとうございました!本当に本当に助けになりました!! – Ryelle

関連する問題