我想创建一个set方法来插入特定地点的最高温度,我希望该温度为Double类型,该方法将检查输入的数字是否为> = 100或<= 100 如果是,则将其插入最高温度范围。 否则我必须抛出一个用户定义的异常,告诉我我输入的数字超出了假定的限制!
我用这种方式编写了Exception和方法:
public class OutOfSensibleLimits extends Exception
{
private Double max;
public OutOfSensibleLimits(Double max)
{
this.max = max;
}
public Double getMax()
{
return max;
}
public String toString()
{
return "The maximum Tempreture you entered: '" + maxTemp +
"' is out of sensible limits.";
}
}
public void setMaxTemp(Double max){
if ( max >= -100 || max <= 100)
{
maxTemp = max;
}
else throw new OutOfSensibleLimits();
}
它给了我一个错误,我做错了什么?
答案 0 :(得分:2)
问题:
toString
方法是不必要的并且令人困惑,因为它永远不会被调用,并且永远不会看到String。 "and it gives me an error,..."
,但未向我们显示任何错误消息。我猜测编译器抱怨你没有正确调用你的类的构造函数,但请不要让我们猜测 - 显示完整的未删节错误消息。if ( max >= -100 || max <= 100)
。这始终为true。您想改用&&
。建议:
toString()
方法。例如:
public class TestSensibleLimits {
private Double maxTemp;
public void setMaxTemp(double max) throws OutOfSensibleLimits {
if (max >= -100 && max <= 100) { // use && not ||
maxTemp = max;
} else
throw new OutOfSensibleLimits(max);
}
public Double getMaxTemp() {
return maxTemp;
}
public static void main(String[] args) {
TestSensibleLimits test = new TestSensibleLimits();
try {
test.setMaxTemp(200);
} catch (OutOfSensibleLimits e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("serial")
public class OutOfSensibleLimits extends Exception {
private static final String FORMAT = "The maximum Temperature you "
+ "entered: %.2f is out of sensible limits.";
public OutOfSensibleLimits(Double max) {
super(String.format(FORMAT, max));
}
}