Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 执行OOP时,无法在if-else中输出字符串_Java_Oop_If Statement - Fatal编程技术网

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

Java 执行OOP时,无法在if-else中输出字符串,java,oop,if-statement,Java,Oop,If Statement,当我在get方法上执行if-else语句时 我无法在intlength中输出检查字符串,我想将Gh设置为“aaaaaaa” 代码是 public String getGh(){ int length = Gh.length(); if (length == 0){ Gh="AAAAA"; }else{ Gh= null; } return this.Gh; } public S

当我在get方法上执行if-else语句时 我无法在
int
length
中输出检查
字符串
,我想将Gh设置为
“aaaaaaa”
代码是

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==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;
}

旁注:
int length=Gh.length()是危险的,它会在
Gh==null
上抛出异常,所以,我该怎么办?带有OOP的java语言是一个非常奇怪的问题。如果你这样做会发生什么;ShowGh();`?试试看,这很有趣。我仍然有你的代码错误错误:找不到符号符号:可变长度位置:类型的变量GhString@KakiLam:很抱歉输入错误,如果是
String
,它应该是
length()
,如果是arrayi,它应该是
length
,但在文本java上仍然没有输出,为什么?谢谢你对我耐心。我的意思是,当我输入一些东西时,它会显示相同的输入,但当输入为空时,它会显示AAAAA和I,使用长度check@Kaki拉姆:是的,这是在
getGh()
中实现的副作用。你想摆脱它吗?