我正在尝试使用构造函数构建一个程序,该程序有三个门并将它们从打开切换到关闭。正面是打开的,侧面是关闭的,背面是关闭的。然后我尝试切换到Front关闭,Side打开,Back打开。我的程序工作正常,但我觉得我没有使用构造函数的正确方法。另外对于我的测试人员类,是否有更好的方法来切换门的状态? 谢谢! 门类
public class Door {
String name, state; // state is either "open" or "closed"
/**
* Constructor class that receives two arguments.
*
* @param name
* @param state
*/
public Door(String name, String state) {
this.name = name;
this.state = state;
}
public String state() {
return state;
}
public void setState(String state) {
this.state = state;
}
public void setName(String name) {
this.name = name;
}
public String name() {
return name;
}
// method sets door state to "open"
public void open() {
state = "open";
} // end open
// method sets door state to "closed"
public void close() {
state = "closed";
} // end close
public String output() {
return "Door name: " + name
+ '\n' + "State of door: " + state;
}
} // end class Door
DoorTester类
public class Doors {
public static void main(String[] args) {
Door front = new Door("Front", "open");
Door side = new Door("Side", "closed");
Door back = new Door("Back", "closed");
System.out.println(front.output());
System.out.println(side.output());
System.out.println(back.output());
if (front.state.equals("open")) {
front.close();
}
System.out.println(front.output());
if(side.state.equals("closed")){
side.open();
}
System.out.println(side.output());
if(back.state.equals("closed")){
back.open();
}
System.out.println(back.output());
}
}
答案 0 :(得分:0)
有一个字符串表示"打开"或者"关闭"有点风险(例如,你输入一个错字(以后很难察觉),你输入" apen"或者#34; clesed"。布尔是一个更好的解决方案因为门可以关闭或打开......
public class Door {
private String name; //remember to put these as private (by default they're package-private)
private boolean isOpen;
/**
* Constructor class that receives two arguments.
*
* @param name
* @param state
*/
public Door(String name, boolean isOpen) {
this.name = name;
this.isOpen = isOpen;
}
public boolean isOpen() {
return isOpen;
}
public void setState(boolean state) {
this.isOpen = state;
}
public void setName(String name) {
this.name = name;
}
public String name() {
return name;
}
// method sets door state to "open"
public void open() {
isOpen = true;
} // end open
// method sets door state to "closed"
public void close() {
isOpen = false;
} // end close
public String output() {
return "Door name: " + name
+ '\n' + "State of door: " + (isOpen ? "open" : "closed");
}
} // end class Door
或者如果你想要"打开"或者"关闭"来自类的响应,只需使用一个简单的操作(称为三元运算符):
public String state() { return isOpen ? "open" : "closed"; }
基本上与:
相同public String state() {
if(isOpen)
return "open";
else
return "closed;
}
同样如Jon所说,有一个setState
和open
/ closed
方法接缝减少......我的建议如下:
public changeState() { isOpen = !isOpen; }
因为你只能打开一扇门,反之亦然......但这一切都取决于你想用它做什么。