gpt4 book ai didi

Java值总是为空?

转载 作者:行者123 更新时间:2023-12-02 10:52:45 25 4
gpt4 key购买 nike

我在 Java 中有一个值始终为 null,但我不明白为什么,因为我正在使用类构造函数设置变量的值。

我有这样的代码:

Driver driverClass = new Driver("<file path redacted>");

然后是下面的内容:

String cfgFilePath;

public Driver(String cfgFile) {
this.cfgFilePath = cfgFile;
}

private ArrayList<String> keys = getKeys(cfgFilePath);
private String a1 = keys.get(0);
private String b1 = keys.get(1);

出于某种原因,IntelliJ IDEA 表示 cfgFilePath 始终为 null。我用Driver类构造函数初始化它,为什么它是空的?当我运行该程序时,出现空指针异常。

最佳答案

keysa1b1 的初始化移至构造函数,如下所示:

public Driver(String cfgFile) {
this.cfgFilePath = cfgFile;
this.keys = getKeys(cfgFilePath);
this.a1 = keys.get(0);
this.b1 = keys.get(1);
}

private ArrayList<String> keys = new ArrayList<>();
private String a1;
private String b1;

关于Java值总是为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com