3 回答
TA贡献1824条经验 获得超8个赞
您可以声明 enum 是Tile类的实例成员
public class Tile {
private final String letter; //holds the letter value of the tile
private final int row; //holds tile row index
private final int column;
private Status flag; // use getter and setter to set flag on using Status enum
public Tile(String l, int r, int c) {
this.letter = l;
this.row = r;
this.column = c;
}
//setter&getter methods
public String toString() {
return this.getLetter()+" "+ this.getRow() +
"," + this.getColumn();
}
TA贡献1839条经验 获得超15个赞
向 Tile 添加布尔值可能会帮助您处理状态。由于只有两种可能的状态(已选择,未选择),因此布尔值可能更有意义。也不要默认添加 getter 和 setter。只有在你需要它们的时候。参考“讲不问原则”
public class Tile {
private final String letter; //holds the letter value of the tile
private final int row; //holds tile row index
private final int column;
private boolean isTileFlagged;
public Tile(String l, int r, int c) {
this.letter = l;
this.row = r;
this.column = c;
isTileFlagged = false; // May be false to being with
}
// add getters/setters only when necessary
public void toggleFlaggedState(){
isTileFlagged = !isTileFlagged;
}
public String toString() {
return this.getLetter()+" "+ this.getRow() +
"," + this.getColumn();
}
// add hashcode, equals if necessary
此外,如果枚举是必要的,它可能是 Tile 类的内部状态,因为它的独立存在可能没有意义。
TA贡献1875条经验 获得超3个赞
使enum作为成员变量class和方法的enum。
像下面这样:-
package com.robo.lab;
public class Tile {
private final String letter; // holds the letter value of the tile
private final int row; // holds tile row index
private final int column;
private Status status;
public Tile(String l, int r, int c,Status status) {
this.letter = l;
this.row = r;
this.column = c;
this.status=status;
}
// setter&getter methods
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String toString() {
return this.getLetter() + " " + this.getRow() + "," + this.getColumn()+","+this.getStatus();
}
public String getLetter() {
return letter;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
package com.robo.lab;
public enum Status {
CHOSEN, NOTCHOSEN;
public static void tileStatus(Status stat) {
switch (stat) {
case CHOSEN: // something
break;
case NOTCHOSEN: // something
break;
}
}
}
package com.robo.lab;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tile obj1= new Tile("AUser", 1, 1,Status.CHOSEN);
System.out.println(obj1.toString());
Tile obj2= new Tile("BUser", 1, 1,Status.NOTCHOSEN);
System.out.println(obj2.toString());
}
}
添加回答
举报