为什么我的函数没有返回正确的值

我是允儿123

我有一个函数,当且仅给定的值包含在声明的枚举中时,该函数设置该值。然后我试图通过 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么我的函数没有返回正确的值键?

为什么我的函数没有在几秒钟内返回正确的值?

为什么我的函数没有返回?

为什么我的函数停止返回正确的值?

为什么我的程序没有返回正确的文件信息?

为什么我的Jsoup代码没有返回正确的元素?

为什么find()没有返回正确的值?

为什么我的函数没有给出正确的输出?

为什么filter + abs函数没有给出正确的值

为什么我的变量没有从Firestore接收正确的值?

为什么我的 for 循环中的值没有正确附加?

为什么日期函数没有返回我预期的输出?

为什么没有从函数返回值?

为什么这个函数似乎没有返回任何值

为什么这个函数没有返回值?

为什么我的 Promise 没有返回任何值?

为什么我的代码没有返回斜边的值?

为什么我可以返回对函数拥有值的引用?

为什么我在 CS50 的 filter(less) (PSET 4) 中的模糊功能没有返回正确的值?

为什么我的代码应该返回以下内容时没有返回?什么是正确的?

函数没有返回正确的值(Python)

替换函数没有返回正确的值

全局函数没有返回正确的值

为什么声明返回值时我的函数没有结束(Node.js和Express.js)

为什么sql函数返回所有计数和单个选择返回正确值?

为什么没有返回值的函数在 perl 中有值?

为什么我的 add 函数没有给我正确的输出?

为什么我的函数没有被调用?

为什么在这个函数中变量没有被更新和正确返回?