【发布时间】:2019-04-13 06:58:03
【问题描述】:
我正在尝试合并
- 对变量的公共访问
- 非静态变量
- 非预定义值
- 一次设定值(最终)
- 整数或整数
更新的代码不起作用,关于“如何做”的答案一定很简单,但我需要帮助:
public class foo
{
public final int smth; //Variable might not have been initialized
public final Integer smthElse; //Variable might not have been initialized
public foo(JSONObject myObj)
{
if(myObj != null) {
try {
int extraParam = Integer.parseInt("ABCD"); //This is just an example for Exception to be called
smth = extraParam;
smthElse = extraParam;
} catch (Exception e) {}
} else {
smth = 1;
smthElse = 2;
}
}
}
附:我不想使用(private int + public getter + private setter)
【问题讨论】:
-
你的代码编译得很好。您可能没有向我们展示您的真实代码。
-
现在错误很明显了:如果 myObj 为空怎么办?在这种情况下你会初始化字段吗?不。因此错误消息,确切地说。
-
@JBNizet 我已经编辑了代码。我想“如果”是“变量可能尚未初始化”的答案。如果我无法将其与任何内容进行比较,我该如何检查代码最后几行中的 final int 以设置默认值?
-
在设置默认值时添加 else 语句
-
你应该遵循 Java 命名约定:类名总是以大写开头。