要通过方法传递的参数

时间:2014-10-23 11:12:47

标签: java

我正在创建一个构造函数,我被告知要做的是:

  • quantity参数将传递给testQuantity方法。”

  • “在此之后,应通过getPrice方法调用productName方法 参数“

这是我到目前为止对于这个构造函数,变量是设置的,我只需要一些帮助。

    public Order (String productName, int quantity) {
        orderNum = orderNum + 1;
        productName = this.productName;
        quantity = testQuantity; 
        if (isValidOrder = true)

5 个答案:

答案 0 :(得分:1)

在这种情况下,构造函数应该是这样的:

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.
    }

答案 1 :(得分:1)

public Order (String productName, int quantity) {
        orderNum = orderNum + 1;
        productName = this.productName;
        quantity = testQuantity; 
        if (isValidOrder = true)
        .....
        testQuantity(quantity);
        getPrice(productName);

testQuantitygetPrice方法中,接收从构造函数传递的参数。

虽然quantity = testQuantity;

,但不确定这行代码是什么

答案 2 :(得分:1)

productName = this.productName;

考虑不要这样做。您的实例变量在声明时被赋值,并且在实例化时已经定义 - 比您只能使用它的值而productName参数是无用的。 或者它没有在声明它的地方给出值 - 那么构造函数的工作是为这个变量赋值,在此之前你不能使用它。

答案 3 :(得分:1)

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!
}

答案 4 :(得分:0)

通过以下代码

  1. 将数量传递给testQuantity方法:testQuantity(quantity);

  2. 获取价格:getPrice(productName);

  3. 祝你好运!!!