Java如何使参数成为另外两个参数的乘法乘积?

时间:2016-04-30 04:12:26

标签: java

我确定这是一个noob问题,但在我正在努力的程序中,我试图将一个变量作为参数传递,这很容易,但我还是因为我试图传递的变量是它前面的两个参数的产物而停滞不前。

我必须为机动车辆创建一个对象,该对象具有车主姓名,车轮数量和升位数的参数,但第四个也是最后一个参数是乘以位移和数字的结果车轮在一起,称为"马力" (虽然我很确定这不是真正计算出的马力。)

在任何情况下,在定义" MotorizedVehicle"我有以下代码。

    /*


public class MotorizedVehicle extends Bicycle {
    int litersDisplaced;
    int horsepower = litersDisplaced * wheelCount;




public MotorizedVehicle(String ownerName, int wheelCount, int litersDisplaced, int horsepower){
    this.ownerName = ownerName;
    this.wheelCount = wheelCount;
    this.litersDisplaced = litersDisplaced;
    this.horsepower = horsepower;

}

    public int getLitersDisplaced() {
        return litersDisplaced;
    }

    public void setLitersDisplaced(int litersDisplaced) {
        this.litersDisplaced = litersDisplaced;
    }

    public int getHorsepower() {
        return horsepower;
    }

    public void setHorsepower(int horsepower) {
        this.horsepower = horsepower;
    }
}

现在,在客户端类中,我有以下代码:

/*

package extracredit4;

/**
 *
 * @author ChetSpalsky
 */
public class VehicleClient {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    MotorizedVehicle car1 = new MotorizedVehicle("Bill", 2, 4, *); //Where I have the * this is where the argument for the "horsepower" variable or method should be, but I don't know what to put here to call the variable that will be litersDisplaced * wheelCount.


}

}

要明确的是,我不能只是把" 8"第四个参数应该在哪里,我必须调用将litersDisplaced和wheelCount相乘的方法。

很抱歉,如果这是一个只会让经验丰富的程序员看到问题的问题之一,但我已经看了一遍,似乎无法找到这个问题的答案,我真的很感激帮助。谢谢!

4 个答案:

答案 0 :(得分:1)

只需输入2 * 4,就像MotorizedVehicle car1 = new MotorizedVehicle("Bill", 2, 4, 2 * 4);

一样

答案 1 :(得分:0)

对于horsepower,你可以完全摆脱这个论点。将构造函数更改为如下所示:

public MotorizedVehicle(String ownerName, int wheelCount, int litersDisplaced){
    this.ownerName = ownerName;
    this.wheelCount = wheelCount;
    this.litersDisplaced = litersDisplaced;
    this.horsepower = this.litersDisplaced * this.wheelCount;

}

答案 2 :(得分:0)

在构造函数中执行乘法:

public MotorizedVehicle(String ownerName, int wheelCount, int litersDisplaced){
    this.ownerName = ownerName;
    this.wheelCount = wheelCount;
    this.litersDisplaced = litersDisplaced;
    horsepower = wheelCount * litersDisplaced;
}

答案 3 :(得分:0)

当你拨打getHorsePower()时,是否不允许省略马力参数并计算马力值?例如,

public MotorizedVehicle(String ownerName, int wheelCount, int litersDisplaced){
    this.ownerName = ownerName;
    this.wheelCount = wheelCount;
    this.litersDisplaced = litersDisplaced;
}

public int getHorsepower() {
    return wheelCount * litersDisplaced;
}

这种方法的好处是,如果您拨打setWheelCount()setLitersDisplaced()getHorsePower()函数将始终返回正确的horsePower值。

您可能希望删除setHorsepower()函数,因为它是一个计算值。