[英]Prevent negative numbers and return previous value in Java?
In setSpeed I am trying to have a validation check on numbers passed through.在 setSpeed 我试图对通过的数字进行验证检查。 If a negative number is passed it should pass the initial value.
如果传递负数,则应传递初始值。 (speed:0) but if I pass a 3 first then a negative number the value returned is 3. I for some reason can't get 0 returned if I pass a negative number first.
(speed:0) 但是如果我先传递一个 3 然后一个负数返回的值为 3。如果我首先传递一个负数,我由于某种原因不能得到 0 返回。
public class Conveyor {
private String type;
private double speed;
public Conveyor(String t, double s) {
type = t;
speed = s;
setSpeed(s);
}
public String getType() {
return type;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double s) {
if (s > 0) {
speed = s;
} else {
speed = speed;
}
}
public double timeToTransport(double distance) {
distance = distance / speed;
return distance;
}
}
Take a look at your constructor:看看你的构造函数:
speed = s;
setSpeed(s);
and your setter:和你的二传手:
public void setSpeed(double s) {
if (s > 0) {
speed = s;
} else {
speed = speed;
}
}
What happens when you put in a negative value is that it is set in the constructor and kept in the setter because of the speed = speed
.当你输入一个负值时会发生什么,因为
speed = speed
它是在构造函数中设置并保存在 setter 中的。
So just remove speed = s
from the constructor and remove the else
-section in the setter.所以只需从构造函数中删除
speed = s
并删除 setter 中的else
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.