Java 创建对象的用户输入
我正在尝试使用用户输入创建一个新对象。我尝试将用户输入分配给变量,但在声明新对象时不知道如何将变量添加到中的新对象。这只是我需要帮助的代码的一部分。我需要帮助的部分是第8行。我知道我可以随意放置一些东西,当我使用set方法时,它会覆盖,但这不是我想要的。先谢谢你Java 创建对象的用户输入,java,user-input,Java,User Input,我正在尝试使用用户输入创建一个新对象。我尝试将用户输入分配给变量,但在声明新对象时不知道如何将变量添加到中的新对象。这只是我需要帮助的代码的一部分。我需要帮助的部分是第8行。我知道我可以随意放置一些东西,当我使用set方法时,它会覆盖,但这不是我想要的。先谢谢你 Scanner input = new Scanner(System.in); System.out.println("Enter the name of the Soda: "); String soda = inp
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);
这取决于
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);