如何更改才能得到所要的输出结果?
public class PersonTest {
private int age = 20;
private String name = "Hello";
public String getInfo()
{
String name = "XiaoBai";
int age = 12;
if (name != null)
{
return "Name: "+ name + "\n" +"age:"+ age; //这里访问的是局部变量
}
return "Name: "+ this.name + "\n" +"age:"+ this.age; //这里访问的是成员变量
}
public static void main(String[] args) {
PersonTest p1 = new PersonTest();
System.out.println(p1.getInfo());
}
}
String name = "XiaoBai";这个地方如何更改,输出的结果才是成员变量的值?
------解决方案--------------------String name = null;
------解决方案--------------------
把变量名name改为其他
------解决方案--------------------你那一行的return "Name: "+ this.name + "\n" +"age:"+ this.age; //这里访问的是成员变量
已经说明了,还有前面if(name!=null)输出局部变量
那么你想return全局变量 可以String name = null;
------解决方案--------------------public class PersonTest {
private int age = 20;
private String name = "Hello";
public String getInfo()
{
String name =null;
int age = 12;
if (name != null)
{
return "Name: "+ name + "\n" +"age:"+ age; //这里访问的是局部变量
}
return "Name: "+ this.name + "\n" +"age:"+ this.age; //这里访问的是成员变量
}
public static void main(String[] args) {
PersonTest p1 = new PersonTest();
System.out.println(p1.getInfo());
}
}
将String name=“XiaoBai”改成String name=null即可