如何使用定义的对象作为输入变量?

时间:2020-03-21 21:40:58

标签: java object boolean polymorphism

我之前定义了Coordinates类,因为它需要两个整数,现在我想在其他类中的某个地方使用它,例如

public boolean isLocationValid( Coordinates location ){
       ...and here I want to define that location should be in the boundaries (for example 0<x<10 and 0<y<10)
    }

但是我不知道,位置对象也不接受x和y!我该怎么办?

在这里找到坐标代码:

import java.util.IdentityHashMap;

public class Coordinates {
    private int x  ;
    private int y ;

    public  Coordinates(){ //default constructor
        this.x = 0;
        this.y = 0;
    }
    public Coordinates(int x, int y){ //parameterized constructor
    this.x = x;
    this.y = y;
    }

    //getter and setter
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    //the outcome of the rows should be in Letters, so I defined the Hashmap for the alphabet
  static   IdentityHashMap<Integer, String> Row = new IdentityHashMap<Integer, String>();
    /*Adding elements to HashMap*/
    static {
        Row.put(0, "A");
        Row.put(1, "B");
        Row.put(2, "C");
        Row.put(3, "D");
        Row.put(4,"E");
        Row.put(5, "F");
        Row.put(6, "G");
        Row.put(7, "H");
        Row.put(8, "I");
        Row.put(9, "J");
        Row.put(10, "K");
        Row.put(11, "L");
        Row.put(12, "M");
        Row.put(13, "N");
        Row.put(14, "O");
        Row.put(15, "P");
        Row.put(16, "Q");
        Row.put(17, "R");
        Row.put(18, "S");
        Row.put(19, "T");
        Row.put(20, "U");
        Row.put(21, "V");
        Row.put(22, "W");
        Row.put(23, "X");
        Row.put(24, "Y");
        Row.put(25, "Z");

    }


    public String toString() {
        return Row.get(getX())+getY();
    }
}

如何从坐标中定义位置变量并在边界中定义它?

1 个答案:

答案 0 :(得分:0)

Coordinates类中有一些吸气剂,因此在isLocationValid()方法中,调用location.getX()location.getY()。扩展您的示例:

public boolean isLocationValid( Coordinates location ){
    // ...and here I want to define that location should be in the boundaries (for example 0<x<10 and 0<y<10)
    return isBetweenMinAndMax(location.getX() && isBetweenMinAndMax(location.getY()))
}

private final int MIN_EXCLUSIVE = 0;
private final int MAX_EXCLUSIVE = 10;
private isBetweenMinAndMax(int value) {
    return value > MIN_EXCLUSIVE && value < MAX_EXCLUSIVE;
}