用户输入以创建对象 [英] user input to create object

查看:22
本文介绍了用户输入以创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

这取决于 SodaMachine 类是如何实现的.如果SodaMachine 的构造函数需要String, int, double 参数,则调用传递它们的构造函数而不指定类型.注意没有必要再次设置(使用setCostOfBottle(), ...)成员,因为这就是你将变量传递给构造函数的原因.

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

然后设置成员:

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

这篇关于用户输入以创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆