[英]Parameter to be passed through a method
我正在创建一个构造函数,我被告知要做的是:
“ quantity
参数将传递给testQuantity
方法。”
“在此之后,应通过传递productName
参数来调用getPrice
方法”
到目前为止,这是我为该构造函数准备的内容,设置了变量,我只需要一些帮助。
public Order (String productName, int quantity) {
orderNum = orderNum + 1;
productName = this.productName;
quantity = testQuantity;
if (isValidOrder = true)
在这种情况下,构造函数应如下所示:
public Order (String productName, int quantity) {
testQuantity(quantity); //Probably this should return a boolean or throw a exception
double price = getPrice(productName); //Probably it should return a quantity.
//other operations needed.
}
public Order (String productName, int quantity) {
orderNum = orderNum + 1;
productName = this.productName;
quantity = testQuantity;
if (isValidOrder = true)
.....
testQuantity(quantity);
getPrice(productName);
在testQuantity
和getPrice
方法中,接收从构造函数传递的参数。
尽管quantity = testQuantity;
但不确定这行代码是quantity = testQuantity;
productName = this.productName;
只是考虑不要这样做。 实例变量在声明时被分配了一个值,并且在实例化时已经被定义-您只能使用它的值,而productName
参数是无用的。 还是在声明的地方没有给出值-然后是构造函数将值分配给该变量,在此之前您不能使用它。
public Order (String productName, int quantity){
// same as you did "orderNum = orderNum + 1" and "orderNum += 1".
// I added "this" in the beginning because "orderNum" is not a variable
// you declared in the constructor so it will be from the class.
// BTW make sure you initialized the variable.
this.orderNum++;
// I think you are doing this part by mistake without understanding. So I commented this part.
// what this code means is: set the value of variable "productName" (that you declared in the
// method, the first parameter) of the value of variable "this.productName" (that you declared
// in the root of the class, like orderNum)
// productName = this.productName;
// The quantity parameter is to be passed to the testQuantity method.
// general way to call a method is <method name>(); "()" means execute
// any information you want to pass as parameter goes inside the parenthesis
testQuantity(quantity);
// Following this a call to the getPrice method should be made passing the productName parameter
// same rules here.
getPrice(productName);
// However, you are not storing the values after you calling the methods.
// if you have any further questions feel free to comment and I will reply asap.
// Good Luck!
}
通过以下代码,
将数量传递给testQuantity方法:testQuantity(quantity);
获得价格:getPrice(productName);
祝好运 !!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.