2017-03-05 49 views
0

我在我的ShoeLibrary類中有一個arraylist。我還有另一個名爲Shoe的類,它擁有這個數組列表中變量的setter和getters。我如何從用戶輸入更改我的數組列表中的值?

ShoeLibrary類

public class ShoeLibrary { 

private ArrayList<Shoe> shoes; 

public ShoeLibrary() { 
    shoes = new ArrayList<Shoe>(); 
    shoes.add(new Shoe("Shoe 1", 100)); // the integer represents stock 
    shoes.add(new Shoe("Shoe 2", 200)); 
    shoes.add(new Shoe("Shoe 3", 300)); 
} 

以我MainActivity GUI類我有一個輸入對話框這需要整數值的用戶輸入,然後將其添加到籃。

我需要一種方法來更新數組列表中的數字(股票),當用戶輸入此值時。我將如何做到這一點。

+0

'Shoe 1'是一種類型,100是數量?如果是這樣,那麼你想從列表中獲得鞋子,然後使用鞋類中的一個setter來更改數量。如果這就是你說的話,那麼我可以提供一些關於代碼的幫助。 –

+0

@ChrisSharp是的,這是正確的 – user982467

+0

下面的答案是否有幫助,或者您是否回答了錯誤的問題? –

回答

0

我假設我的評論是正確的,並且寫了一些基本的代碼來向你展示這是如何完成的。您需要對其進行更改以適應您的情況並從GUI獲取客戶數據。您還需要進行錯誤檢查。

public class Sandbox { //opens class 

    public static void main(String[] args) { 
     ArrayList<Shoe>shoes = new ArrayList<Shoe>(); 
     shoes.add(new Shoe("Shoe 1", 100)); // the integer represents stock 
     shoes.add(new Shoe("Shoe 2", 200)); 
     shoes.add(new Shoe("Shoe 3", 300)); 
     Shoe temp; 
     String shoeSelected = "Shoe 3"; // you need to use the customer's input here 
     int numSeleted = 20; // again, you need this data from the customer input 
     for (int i = 0; i < shoes.size(); i++) { 
      temp = shoes.get(i); 
      if(temp.name == shoeSelected) { 
       shoes.get(i).setQuantity(temp.quantity - numSeleted); 
       System.out.println(shoes.get(i).name); 
       System.out.println(shoes.get(i).quantity); 
      } 
     } 
     System.out.println("wait"); 
    } 

} 

class Shoe { 
    String name; 
    int quantity; 

    public Shoe(String name, int quantity) { 
     this.name = name; 
     this.quantity = quantity; 
    } 

    public void setQuantity(int quantity) { 
     this.quantity = quantity; 
    } 
} 
+0

爲什麼你在主要方法中放置了數組列表和代碼? – user982467

+0

因爲我不知道你的類是如何設置的,我也沒有你的GUI界面。我把它放在那裏,所以我可以向你展示如何去修改列表中的項目。來電和列表可以來自任何地方。 –

相關問題