gpt4 book ai didi

java - 进行 OOP 时,无法在 if else 中输出字符串

转载 作者:行者123 更新时间:2023-12-02 11:19:43 25 4
gpt4 key购买 nike

当我在 get 方法上执行 if else 语句时我无法在 int length 中输出检查 String 并希望将 Gh 设置为 "AAAAA"代码是

public String getGh(){
int length = Gh.length();
if (length == 0){
Gh="AAAAA";
}else{
Gh= null;
}
return this.Gh;
}
public String ShowGh() {
return ("Title: "+this.Gh);

输出不正常,请帮忙

最佳答案

您应该记住,String 很可能为 null,因此

int length = Gh.length();

抛出异常。这就是为什么在执行 Gh.length 之前必须手动检查 null null == Gh 的原因。我建议这样:

private String Gh = ""; // no null but empty string by default

...

public String getGh {
// If Gh is null or empty, assign "AAAAA"; empty otherwise
Gh = (null == Gh || 0 == Gh.length())
? "AAAAA"
: "";

return Gh;
}

//TODO: Turn ShowGh() into camel case: showGh()
public String ShowGh() {
//DONE: you probably mean "getGh()" instead of Gh
// return ("Title: " + Gh);
// getGh() tries to get Gh, change its value to "AAAAA" and we have "Title: AAAAA"
return "Title: " + getGh();
}

编辑:如果您想消除 getGh() 中的副作用并以典型方式实现逻辑:

public String getGh {
// Just return Gh value
return Gh;
}

public String setGh(String value) {
// If Gh is null or empty, assign "AAAAA"; empty otherwise
Gh = (null == value || 0 == value.length())
? "AAAAA
: value;
}

关于java - 进行 OOP 时,无法在 if else 中输出字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50021503/

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