我需要将结果看作boolean
result:true。但是我需要以非常规方式来做到这一点。使用其他方法处理其他方法中的异常catch
import java.io.IOException;
public class FlashLight {
private Bulb bulb;
private Battery[] batteries;
public void on() {
try {
if (this.IsThereEnoughPower()) {
this.bulb.setOn(true);
for (Battery b : batteries) {
b.setPower(b.getPower() - this.bulb.getBrightness());
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
this.setBatteries(new Battery[4]);
}
}
我需要赶上方法on()
例外,但我只能修改方法:DetermineIfFlashlightCanBeTurnedOn
public boolean DetermineIfFlashlightCanBeTurnedOn() throws IOException {
return bulb != null && DetermineIfBatteriesAreInstalled() && IsThereEnoughPower();
}
private boolean DetermineIfBatteriesAreInstalled() throws IOException {
if (batteries.length < 4) {
throw new IOException(Math.abs(-4 + batteries.length));
}
for (Battery b : batteries) {
if (b == null) {
return false;
}
}
return true;
}
private boolean IsThereEnoughPower() {
for (Battery b : batteries) {
if (b.getPower() < MIN_BATTERY_POWER) {
return false;
}
}
return true;
}
private static void testLatarki(String... args) {
FlashLight flashlight = new Flashlight();
System.out.println(flashlight.DetermineIfFlashlightCanBeTurnedOn());
}
}
例外只能在被捕获()方法。 DetermineIfBatteriesAreInstalled()确定IfFlashlightCanBeTurnedOn 必须标记为:throws IOException。
目前尚不清楚你的问题是什么 –
好简单地说,我需要正确编译DetermineIfFlashlightCanBeTurnedOn()方法,并使用on()方法捕获异常,以便在控制台中显示“true”。 – SpicyJam