2014-02-16 59 views
0

我正嘗試使用用戶輸入創建新對象。我嘗試將用戶輸入分配給變量,但不知道如何將變量添加到聲明新對象的新對象中。這只是我需要幫助的代碼的一部分。部分我需要幫助是第8行。我知道我可以隨意放些東西,當我使用我的設置方法時,它會覆蓋,但這不是我想要的。謝謝用戶輸入以創建對象

Scanner input = new Scanner(System.in); 
    System.out.println("Enter the name of the Soda: "); 
    String soda = input.nextLine(); 
    System.out.println("Inventory count?: "); 
    int product = input.nextInt(); 
    System.out.println("Cost of Soda?: "); 
    double cost = input.nextDouble(); 
    SodaMachine one = new SodaMachine(String soda, int product, double cost); 
    one.setCostOfBottle(cost); 
    one.setInventory(product); 
    one.setNameOfSoda(soda); 

回答

1

這取決於如何SodaMachine類實現。如果SodaMachine的構造函數需要String, int, double參數,則調用傳遞構造函數而不指定類型的構造函數。 注意它沒有必要再次設置(使用setCostOfBottle(), ...)成員,因爲這就是爲什麼你要傳遞變量給構造函數。

SodaMachine one = new SodaMachine(soda, product, cost); 

如果你的構造函數不接受參數:

SodaMachine one = new SodaMachine(); 

後來設置的成員:

one.setCostOfBottle(cost); 
one.setInventory(product); 
one.setNameOfSoda(soda);