使用简单的Java Point
类,我希望将X和Y值限制为双精度数,必须在-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 + "]");
}
}
答案 0 :(得分:2)
这可能是我做的:
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);
}
}
答案 1 :(得分:0)
如果X和Y值始终来自同一个域,那么您可以将它们封装在一个为您进行检查的类中:
class Coord {
private final double scalarValue;
public Coord(double scalarValue) throws IllegalArgumentException {
if (Math.abs(scalarValue) > MAX_COORD) {
throw new IllegalArgumentException("Coordinate out of range");
}
this.scalarValue = scalarValue;
}
public double getScalar() {
return scalarValue;
}
}
将检查放在一个位置,并允许您在将来扩展坐标功能而不会弄乱您的Point类。它还明确地使坐标不可变,这可能是一个好主意(取决于用例)。
然后你的点构造函数变为:
public Point(Coord x, Coord y);