我正在尝试写两个类:
一个用于具有唯一ID和方向的实例的机器人。 和另一个方向类,将枚举用于机器人的方向。 我试着用以下方式写它,但我想我错过了一些东西......
package Q1;
public class Robot {
static int IDGenerator = 1000; //ID generator for class Robot
int RoboID; //The ID of the robot
Direction direction; //The Direction the robot is facing
//Constructor for Robot
public Robot(int dir){
this.direction = new Direction(dir);
this.RoboID = IDGenerator;
IDGenerator++;
}
}
枚举的类:
package Q1;
public enum Direction{
UP(1), RIGHT(2), DOWN(3), LEFT(4);
private final int dir;
//constructor for Direction enum for a robot
private Direction(int dir){
this.dir = dir;
}
//return facing direction of a robot
public int getDirection(){
return this.dir;
}
}
答案 0 :(得分:3)
枚举不会通过new
实例化;相反,它们在编译时有一组已定义的实例。只需像这样直接访问实例:
public Robot(Direction dir) {
this.direction = dir;
}
您可以调用此构造函数,例如像这样:
Robot bot = new Robot(Direction.UP);
答案 1 :(得分:2)
假设您不想在Direction
构造函数中使用Robot
参数,那么经典的解决方案是在枚举中提供静态方法以返回给定的正确值输入:
public enum Direction {
//... code omitted
public static Direction fromInt(int direction) {
for (Direction d : values()) {
if (direction == d.getDirection()) {
return d;
}
}
throw new NoSuchElementException(Integer.toString(direction));
}
}
然后在构造函数中使用它:
//Constructor for Robot
public Robot(int dir){
this.direction = Direction.fromInt(dir);
this.RoboID = IDGenerator;
IDGenerator++;
}
答案 2 :(得分:0)
虽然构造函数是私有的,但您正在调用this.direction = new Direction(dir);
。在枚举中提供(静态)方法以将整数转换为正确的方向。
编辑:或使用
public Robot(Direction direction) {
...
代替。
答案 3 :(得分:0)
尝试类似
的内容package SO;
public class Robot {
static int IDGenerator = 1000; // ID generator for class Robot
int RoboID; // The ID of the robot
Direction direction; // The Direction the robot is facing
// Constructor for Robot
public Robot(Direction dir) {
this.direction = dir;
this.RoboID = IDGenerator;
IDGenerator++;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "Direction: " + direction;
}
public static void main(String[] args) {
Robot r = new Robot(Direction.UP);
System.out.println(r);
}
}
创建Robot的对象时传递方向。
除此之外,我个人会在这里使用构建器模式,类似于
package SO;
public class Robot {
static int IDGenerator = 1000; // ID generator for class Robot
int RoboID; // The ID of the robot
Direction direction; // The Direction the robot is facing
public Robot setDirection(Direction dir){
this.direction = dir;
return this;
}
public Robot setId(int id){
this.RoboID = id;
return this;
}
// Constructor for Robot
@Override
public String toString() {
// TODO Auto-generated method stub
return "Direction: " + direction;
}
public static void main(String[] args) {
Robot r = new Robot();
r = r.setDirection(Direction.UP).setId(212);
System.out.println(r);
}
}