为什么我的私有变量在使用 getter-setter 方法后没有更新?

问题描述 投票:0回答:0

我正在制作一个程序,它要求用户输入名称。我以前做过两次几乎相同的事情。但是,由于某种原因,当我调用该函数进行打印时,该程序给了我“null”。在 int 变量之前,我只专注于此,但是,是的,它们也有同样的问题。

我的代码是这样开始的

class Main {
    public static void main(String[] args){
        int choice; 
        
        //Sets the student's name
        Student scholar = new Student(); //Access to Student.java
        Scanner nameInput = new Scanner(System.in); 
        System.out.println("Please enter your name"); 
        String newName = nameInput.nextLine(); //applies the string to a variable
        scholar.setName(newName); //Calls a method to input the name
    }

    public static void exitTutor(){
        Student scholar = new Student();
        scholar.results(""); 
        System.exit(0);
    }
}

class Student {
    private String studentName;

    public void setName(String studentName){
        this.studentName = studentName;
    }

    public void results(String result){
        System.out.println("Final Results for " + studentName);
    }
}

输出:

Final Results for null

我什至复制并粘贴了我在其他程序中使用的代码,但它仍然是空的。

编辑:我添加了结果调用。我知道使用“”和 0,但稍后我会用用户输入替换它们

java string instance private setter
© www.soinside.com 2019 - 2024. All rights reserved.