我有一个函数,当且仅给定的值包含在声明的枚举中时,该函数设置该值。然后我试图通过 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 ;
}
我目前正在学习 enum 并且对它不是很熟悉。我只是通过 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)));
}
}
在枚举中,您只是声明了名称,而不是值。但是,在您的方法中,您正在检索测试的值。这不是预期的行为。
做:
if (b.toString().equals(branchLocation)) {
this.BranchName = branchLocation;
return true;
}
或为 Enum 中的每个名称定义一个值:
public enum BranchLocations {
ONE("ONE"),
TWO("TWO"),
THREE("THREE"),
FOUR("FOUR"),
FIVE("FIVE")
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句