此课程的要求如下:
编写一个名为Elevator的类,该类应包含以下成员变量:
- currentFloor(int)
- elevatorState(一个int常量,IDLE,TO_SOURCE或TO_DESTINATION)
- request(表示正在处理的请求的请求对象,如果Elevator处于空闲状态,则为null)
您还应该为此课程提供以下内容:
默认构造函数,将
request
设置为 null ,将elevatorState
设置为 IDLE ,将currentFloor
设置为1。
每个变量的访问器和mutator方法。 表示IDLE,TO_SOURCE和TO_DESTINATION的最终变量。
继承我所拥有的:
public class Elevator {
private int currentFloor;
private int elevatorState;
private Elevator request;
public Elevator(){
currentFloor = 1;
elevatorState = ; //this is my problem
request = null;
}
}
我感到困惑,因为它说IDLE,TO_Source和TO_DESTINATION是整数常量,但它们不是字符串吗?
任何澄清都会非常有用。
答案 0 :(得分:3)
基本上,要问的是3个int常量:
public static final int IDLE = 0;
public static final int TO_SOURCE = 1;
public static final int TO_DESTINATION = 2;
public Elevator(){
currentFloor = 1;
elevatorState = IDLE; //this is no longer my problem
request = null;
}
但是,如果你想成为一个先生花哨的裤子并正确地使用OOP (可能没有教过的东西),你可以使用Enum!
public enum ElevatorState {
IDLE, TO_SOURCE, TO_DESTINATION
}
然后在你的课堂上:
public class Elevator {
private ElevatorState elevatorState;
private int currentFloor;
private Elevator request;
public Elevator() {
currentFloor = 1;
elevatorState = ElevatorState.IDLE; //this is no longer my problem
request = null;
}
}
我的Java有点生疏,但这应该可以使用。
答案 1 :(得分:0)
这里有一个可能解决问题的方法:
public class Elevator
{
private static final int IDLE = 0;
private static final int TO_SOURCE = 1;
private static final int TO_DESTINATION = 2;
private int currentFloor;
private int elevatorState;
private Elevator request;
public Elevator(){
currentFloor = 1;
elevatorState = IDLE; //this is my problem
request = null;
}
public int getCurrentFloor() {
return currentFloor;
}
public void setCurrentFloor(int currentFloor) {
this.currentFloor = currentFloor;
}
public int getElevatorState() {
return elevatorState;
}
public void setElevatorState(int elevatorState) {
if( elevatorState == IDLE ) setRequest( null );
this.elevatorState = elevatorState;
}
public Elevator getRequest() {
return request;
}
public void setRequest(Elevator request) {
this.request = request;
}
}