Search code examples
javaarraylisttostring

Return value of ArrayList


I'm doing a Java practice which told me to write a toString method, but I'm stuck with the return value of ArrayList. For more instruction, please read the comment of the toString part.

import java.util.ArrayList;
import java.util.Arrays;

public class Student {
    /** The student's name */
    private String name;
    /** Course codes which the student is enrolled in */
    private ArrayList<String> courses;

    /** Creates a new student with the given name.
     * @name the student's name
     */
    public Student(String name) {
        this.name = name;
        this.courses = new ArrayList<String>();
    }

    /** Enrol in a course.
     * @param course course code of the course being enrolled in. e.g. CSSE2002
     */
    public void addCourse(String course) {
        this.courses.add(course);
    }

    /**
     * Returns the human-readable string representation of this student.
     * The format of the string to return is
     * "'name': courses='courseCodes'" without the single quotes,
     * where 'name' is this student's name and 'courseCodes' is a comma-separated
     * list of this student's enrolled courses.
     * For example, if the student is enrolled several courses:
     * "John Smith: courses=CSSE2002,DECO3801".
     * If the student is enrolled in one course: "John Smith: courses=CSSE2002".
     * If the student is not enrolled in any courses: "John Smith: courses=NO_COURSES".
     * @return string representation of this student
     */
    public String toString() {
        
        Boolean CheckArray = courses.isEmpty();
        if(CheckArray == true){
            return this.name + ":" + " courses=NO_COURSES";
        }else{
            return this.name + ":" + " courses=" + this.courses;
        }
        
    }
}

I keep having this error on my test cases when running the program, enter image description here

I don't know how to get ride of the extra [], it seems like a silly question and would be nice if someone can help. Thank you!


Solution

  • According to the code comments, The test cases seem to expect an output such as:

    John Smith: courses=CSSE2002,DECO3801
    

    You can use String.join to join the course codes with the delimiter ,:

    return this.name + ":" + " courses=" + String.join(",", this.courses);