为什么getName()返回null?

ConfusedCoder:

编辑:感谢所有的答案!我不知道pList.java 中的对象pMain.java 中的对象不同我将其作为参数传递,现在可以正常工作。谢谢!

在Main.java中:

        System.out.println("Enter your name:");
        String name = scan.next();
        name+=scan.nextLine();

        String words[]=name.split("\\s");  
        String capitalizeWord="";  
        for(String w:words){  
            String first=w.substring(0,1);  
            String afterfirst=w.substring(1);  
            capitalizeWord+=first.toUpperCase()+afterfirst+" ";  
        }

        Person p = new Person(capitalizeWord);

In Person.java

    private String name;
    private int age;

    Person(String newName){
        name=newName;
    }

    Person(int newAge){
        age=newAge;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

在List.java中:

public void printInvoice(){
        System.out.println("Enter your age:");
        int age = scan.nextInt();

        Person p = new Person(age);
        System.out.println("Thank you for shopping with us, "+p.getName());
}

最后的输出是

Thank you for shopping with us, null

我不知道为什么会这样。我做错什么了吗?我认为代码正确吗?

始终学习:

每次调用构造函数时,都会得到对象的不同实例。Main.java使用名称创建的对象存储在p仅存在于范围内的局部变量Main.java在其中List.java创建一个带有年龄但没有名称的第二个对象。它也存储在一个名为的变量中,p但是该变量List.java在一个范围内,与先前创建的对象无关。

听起来您想将名称添加到较早的对象,而不是创建新的对象。为此,您应该将第一个对象作为参数传递给添加年龄的代码,也许像这样:

public void addAge(Person p) {
  System.out.println("Enter your age:");
  int age = scan.nextInt();
  p.setAge(age);  // will have to make this method in the Person class
  System.out.println("Thank you for shopping with us, "+p.getName());
}

调用Person p = new Person(age);将给出一个没有名称的全新Person对象。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章