我正在編寫一個基於註冊家中電器正在使用的能量消耗量的程序。到目前爲止,我已經創建了各種儀表類,例如WaterMeter,GasMeter等,其中需要使用空值方法存儲值,我還創建了具有用於記錄每個電器內能量消耗的方法的電器類。我現在正在處理的是應用存儲在構造函數中的能量值,將這些值放入一個timePasses()
方法中,然後這些方法將這些值返回到其特定儀表的方法,以便它們可以註冊。這是我到目前爲止有:如何構造一個需要從構造函數中傳遞值的方法?
電器類的例子:
public class ElectricShower extends Shower
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int x = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
@Override
public int currentState()
{
if (x == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
@Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 1;
}
public void shower()
{
//call timePasses() method
}
@Override
public int timePasses()
{
if(x == isOff)
return 0;
else
{
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 12 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 4 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
表例如:
public class ElectricMeter
{
public int incrementConsumed(int value)
{
}
public int incrementGenerated()
{
}
public boolean canGenerate()
{
}
public String getConsumed()
{
}
public String getGenerated()
{
}
}
我下一步需要做的是:
- 取值爲
electricityUse
和waterUse
和他們timePasses()
其他staement - 內
timePasses()
else語句中存儲,地方electrcityUse
值在ElectricMeter
類中incrementGenerated()
方法,爲waterUse
變量這樣做。
UPDATE
類已更新,仍然在努力找出如何使它工作。
感謝您的反饋,我對「私人ElectricMeter(){}」線路有點困惑。首先這是做什麼的?其次,當我實現它時,我可以錯誤地說構造函數不能被應用,因爲它沒有參數,它需要int,int,int,int。 – Tom
這只是爲了防止代碼的其他部分創建儀表的實例。如果出現該錯誤,ElectricMeter似乎從超類繼承。這隻適用於米不從任何東西繼承。 @Tom – Sweeper
儀表類繼承了一個名爲Meter的超類。我已經在我的問題中更新了我的課程,但仍然無法完全弄清楚如何使其工作。謝謝回覆。 – Tom