4 回答
TA贡献1827条经验 获得超8个赞
public void setMultiplier(double multiplier) { // method head
if (multiplier == 1.08 * 1.06 || multiplier == 1.08 || multiplier == 1.06) {
this.multiplier = multiplier; // here the field variable is overwritten
}
throw new IllegalArgumentException("exception message");
}
你忘了写你的类的字段变量。
setter 应该覆盖字段变量。setter 应该覆盖字段变量。他没有返回任何内容,因此在方法头中返回 void 而不是 boolean 。如果参数错误,抛出异常(尽可能有意义)。
提示:我不会将 1.06 或 1.08 等常量分布在代码中的任何位置。您可以将其定义如下:
public class student {
private static final double MEANINGFUL_NAME_0 = 1.06;
private static final double MEANINGFUL_NAME_1 = 1.08;
// other code below
}
优点:如有必要,您只需在一处更改常量。您错过并写 1.07 而不是 1.06 的可能性较低。
TA贡献1895条经验 获得超3个赞
可能是常量的用例:
private static final double ONE_DOT_ZERO_SIX = 1.06f;
private static final double ONE_DOT_ZERO_EIGHT = 1.08f;
/**
* Just to know if it is valid
*/
public boolean setMultiplier(double multiplier) {
return (multiplier == ONE_DOT_ZERO_SIX || multiplier == ONE_DOT_ZERO_EIGHT
|| multiplier == (ONE_DOT_ZERO_SIX * ONE_DOT_ZERO_EIGHT));
}
/**
* Return the multiplier if it is valid, otherwise 1
*/
public double setMultiplier(double multiplier) {
if (multiplier == ONE_DOT_ZERO_SIX || multiplier == ONE_DOT_ZERO_EIGHT
|| multiplier == (ONE_DOT_ZERO_SIX * ONE_DOT_ZERO_EIGHT)) {
return multiplier;
} else {
// return any invalid multiplier, this one doesn't change values at least
return 1;
}
}
/**
* Set the correct multiplier or a substitute
*/
public void setMultiplier(double multiplier) {
if (multiplier == ONE_DOT_ZERO_SIX || multiplier == ONE_DOT_ZERO_EIGHT
|| multiplier == (ONE_DOT_ZERO_SIX * ONE_DOT_ZERO_EIGHT)) {
this.multiplier = multiplier;
} else {
// return any invalid multiplier, this one doesn't change values at least
this.multiplier = 1;
}
}
TA贡献1890条经验 获得超9个赞
Asetter应该更新一个值,并且不返回值(getter的角色),因此它的返回类型应该是void而不是boolean
public void setMultiplier(double multiplier) {
if( multiplier == 1.08 * 1.06 || multiplier == 1.08 || multiplier == 1.06 ) {
this.multiplier = multiplier;
}
}
TA贡献2037条经验 获得超6个赞
我认为您只是忘记实际设置新值。
因此,如果你这样做,它应该可以工作:
public void setMultiplier(double multiplier) {
if( multiplier == 1.08 * 1.06 || multiplier == 1.08 || multiplier == 1.06 ) {
this.multiplier = multiplier;
}
}
此外,setter 通常void不是布尔值,并且没有返回值。
添加回答
举报