玩转简单的 Java Point
我想将 X 和 Y 值限制为 double 值,并且必须在 -10 到 10 范围内(包括 -10 和 10)。我已经编写了一些代码,但距我编写 java 已经很多年了,我想知道现代 Java 中是否会这样编写:
public class Point {
private double x;
private double y;
public Point(double x, double y) {
constrain("x", x);
constrain("y", y);
this.x = x;
this.y = y;
}
// is there a cleaner/shorter way of handling this, such as a direct way of declaring a
// subtype of double that I could use in method signatures?
protected static void constrain(String name, double val) {
if ( val < -10 || val > 10 ) {
throw new IllegalArgumentException(name + " must be between -10 and 10");
}
}
public double getX() { return x; }
public void setX(double x) {
constrain("x", x);
this.x = x;
}
public double getY() { return y; }
public void setY(double y) {
constrain("y", y);
this.y = y;
}
@Override
public String toString() {
return ("[" + x + "," + y + "]");
}
}
最佳答案
我可能会这样做:
public class Point
{
private static final double X_MIN = -10.0, X_MAX = 10.0;
private static final double Y_MIN = -10.0, Y_MAX = 10.0;
private double x, y;
public Point(double x, double y) throws IllegalArgumentException
{
setX(x);
setY(y);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public void setX(double x) throws IllegalArgumentException
{
if (x < X_MIN || x > X_MAX)
{
throw new IllegalArgumentException("X out of range.");
}
this.x = x;
}
public void setY(double y) throws IllegalArgumentException
{
if (y < Y_MIN || y > Y_MIN)
{
throw new IllegalArgumentException("Y out of range");
}
this.y = y;
}
@Override
public String toString()
{
return String.format("[%.1f,%.1f]", x, y);
}
}
关于java - 惯用的 Java : constraining data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27890776/