我有一个函数,如果声明的枚举仅包含给定的值,则可以设置该值。然后,我试图通过get方法获取值,但是我正在获取默认值。 setter方法没有获取新值并进行更新。
public enum BranchLocations {ONE,TWO,THREE,FOUR,FIVE};
private String BranchName ="Branch Name";
public boolean setBranchLocation(String branchLocation) {
for (BranchLocations b : BranchLocations.values()) {
if (b.name().equals(branchLocation)) {
this.BranchName = branchLocation;
return true;
}
}
return false;
}
public String getBranchLocation() {
return this.BranchName ;
}
我目前正在学习枚举,对此并不十分熟悉。我只是通过for循环和.equals方法
检查值是否包含在枚举中public class Main {
public static void main(String[] args){
Bank bank = new Bank("LhblVEWZXmtjn3gMykBaqfN& &h", Bank.BranchLocations.values()[0]);
System.out.println(Bank.BranchLocations.values()[0]);
System.out.println(Bank.BranchLocations.values()[1].toString());
String newBranchLocation = Bank.BranchLocations.values()[1].toString();
System.out.println(bank.getBranchLocation());
bank.setBranchLocation(newBranchLocation);
System.out.println(bank.getBranchLocation());
System.out.println(
(bank.setBranchLocation(newBranchLocation) && bank.getBranchLocation().equals(newBranchLocation)));
}
}
答案 0 :(得分:0)
public enum BranchLocations {
ONE("ONE"),
TWO("TWO"),
THREE("THREE"),
FOUR("FOUR"),
FIVE("FIVE");
private String BranchName = new String();
BranchLocations(String val){BranchName = val;}
public String getBranchLocation() {return BranchName;}
public boolean setBranchLocation(String branchLocation) {
for (BranchLocations b : BranchLocations.values()) {
if (b.name().equals(branchLocation)) {
this.BranchName = branchLocation;
return true;
}
}
return false;
}
}
答案 1 :(得分:-1)
在枚举中,您只是声明了名称,而不是值。但是,在您的方法中,您正在检索测试的值。这不是预期的行为。
要做:
if (b.toString().equals(branchLocation)) {
this.BranchName = branchLocation;
return true;
}
或为枚举中的每个名称定义一个值:
public enum BranchLocations {
ONE("ONE"),
TWO("TWO"),
THREE("THREE"),
FOUR("FOUR"),
FIVE("FIVE")
};