Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

java - program printing extra null that I can't seem to get rid of

public class Student {
    
    private String courses = null;
    
    }
.....Some code here.......
    
    //Enroll in courses
    public void enroll() {
        //Get inside a loop and user hits Q
        do { 
            System.out.print("Enter Course to Enroll(Q to quit): ");
            Scanner in = new Scanner(System.in);
            String course = in.nextLine();
            if (!course.equals("Q")) {
                courses = courses + "
 " + course;
                tuitionBalance = tuitionBalance + costOfCourse;
            
            }
            else{ break; }      
        }while ( 1!= 0);

    }


......Some code here......
    
    //Show Status
    public String showInfo() {
        return "Name: " + firstName + " " + lastName + 
                "
Grade level: " + gradeYear +
                "
Student ID: " + studentId +
                "
Courses Enrolled:" + courses +
                "
Balance: $" + tuitionBalance;
    }


}

Everything seems to be running just fine. But there's an extra null printed after the Courses Enrolled that sticks out like a sore thumb. How could I get rid of it? I've tried setting the String variable courses to null and also without assigning but doesn't seem to affect the result

Name: Frank Kuo
Grade level: 1
Student ID: 11001
Courses Enrolled:null
 Math101
Balance: $0
question from:https://stackoverflow.com/questions/65855279/program-printing-extra-null-that-i-cant-seem-to-get-rid-of

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can replace private String courses = null; with private String courses = ""; to get rid of the null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...