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");
}
您忘记编写类的字段变量。
设置器应覆盖字段变量。设置器应覆盖字段变量。他不返回任何东西,因此在方法头中为void而不是布尔值。如果参数错误,则抛出异常(尽可能有意义)。
提示:我不会在代码中的任何地方分发诸如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的可能性更低。
,
setter
应该更新一个值,并且不返回值(getter
的角色),因此它的返回类型应该是void
而不是boolean
public void setMultiplier(double multiplier) {
if( multiplier == 1.08 * 1.06 || multiplier == 1.08 || multiplier == 1.06 ) {
this.multiplier = multiplier;
}
}
,
我认为您只是忘了实际设置新值。
因此,如果您这样做,它应该可以工作:
void
此外,setter通常是this.setState((state,props) => {
return {
counter: state.counter + 1
}
});
而不是布尔值,并且没有返回值。
,
可能是常量的用例:
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;
}
}
本文链接:https://www.f2er.com/3167826.html