有关CodeHS的APCS分配问题

时间:2018-04-17 17:39:32

标签: java oop

嗨,我正在研究CodeHS问题,并且充满信心地完成了它,但却犯了错误。我正在寻找我的错误和有用的反馈。谢谢!

*问题说明如下:

我们有一个简单的电池类。向Battery添加两个静态字段, totalVoltage和numOfBatteries。另外,改变构造函数以便 Battery类跟踪两个新的静态变量。 每次构建新电池时,numOfBatteries应增加1,并且总电压应增加当前正在构建的电池的新电压。 提示:totalVoltage应为double *

Batterytester是:

public class BatteryTester extends ConsoleProgram
{
    public void run()
    {
        Battery aaBattery1 = new Battery(1.5);
        System.out.println("Total voltage: " + Battery.totalVoltage);
        System.out.println("Total batteries: " + Battery.numOfBatteries);

        Battery aaBattery2 = new Battery(1.5);
        System.out.println("Total voltage: " + Battery.totalVoltage);
        System.out.println("Total batteries: " + Battery.numOfBatteries);

        Battery aaBattery3 = new Battery(1.5);
        System.out.println("Total voltage: " + Battery.totalVoltage);
        System.out.println("Total batteries: " + Battery.numOfBatteries);

        Battery aaBattery4 = new Battery(1.5);
        System.out.println("Total voltage: " + Battery.totalVoltage);
        System.out.println("Total batteries: " + Battery.numOfBatteries);

    }
}

我的代码如下:

public class Battery
{
    private double voltage;
    public static int numOfBatteries;
    public static double totalVoltage;

    //adds the new fields to constructor 
    public Battery(double voltage, double totalVoltage, int numOfBatteries)
    {
        this.voltage = voltage;
        this.totalVoltage = totalVoltage;
        this.numOfBatteries = numOfBatteries;
        numOfBatteries++;
        totalVoltage += voltage; //increments total voltage with voltage param
    }

    public double getVoltage()
    {
        return this.voltage;
    }

    public static int numOfBatteries()
    {
        return this.numOfBatteries;
    }

    public static double totalVoltage()
    {
        return this.totalVoltage;
    }
    //all of these return the values
}

2 个答案:

答案 0 :(得分:0)

thisnumOfBatteries()方法不需要totalVoltage(),因为静态方法无法访问this

答案 1 :(得分:0)

电池应该只带有一个参数,而您只有三个。只需删除totalVoltage和numOfBatteries,您的代码将被修复。就像另一个人所说的那样,对于您创建的两个静态方法,您不需要这样做。