Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 创建对象的用户输入_Java_User Input - Fatal编程技术网

Java 创建对象的用户输入

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

我正在尝试使用用户输入创建一个新对象。我尝试将用户输入分配给变量,但在声明新对象时不知道如何将变量添加到中的新对象。这只是我需要帮助的代码的一部分。我需要帮助的部分是第8行。我知道我可以随意放置一些东西,当我使用set方法时,它会覆盖,但这不是我想要的。先谢谢你

   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);