user input to create object

核能气质少年 提交于 2020-01-22 02:11:52

问题


I'm trying to create a new object using a user input. I tried assigning the user input to variables but don't know how to add the variables to the new object in the when I declare the new object. This is just the part of my code that i need help with. part i need help with is line 8. i know i can just put something random and when i use my set methods it will overwrite but that's not what I want. thank you in advance

   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:


It depends in how is SodaMachine class implemented. If the constructor of SodaMachine expects String, int, double parameters, call the constructor passing them without specifying the type. Note that it's not necessary to set (using setCostOfBottle(), ...) the members again, because that's why you are passing the variables to the constructor.

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

If your constructor doesn't accept parameters:

SodaMachine one = new SodaMachine();

and set the members later:

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


来源:https://stackoverflow.com/questions/21805956/user-input-to-create-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!