简体   繁体   中英

String ArrayList returning null values

I'm new to java and doing some arraylist work, and when compiling my lists just return null values instead of names i have typed in.

I don't undersand why this is so, so if anyone could advise/help me that would be great.

Thanks in advanced.

Here is my main code

import java.util.*;

public class StudentData 
{
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        ArrayList<Student> studentList = new ArrayList<Student>();
        String yesNo = "true";
        do
        {
            System.out.println("Enter student's name: ");
            String name = in.next();
            Student s = new Student();   
            studentList.add(s);
            String input;
            do
            {   
                System.out.println("Would you like to enter data for another student? Yes/No ");
                yesNo = in.next();
                }
            while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
            }   
        while (yesNo.equalsIgnoreCase("YES"));


        for(int i = 0; i < studentList.size(); i++)
        {
            System.out.println(studentList.get(i).getName());
            }
        }
    }

And

class Student 
{
    private String studentName;

    public StudentData(String name)
    {
        setName(name);
    }
    public String getName()
    {
        return studentName;
        }
    public void setName(String name)
    {
        studentName = name;
        }
    }

You're creating a student but didn't set the name :

            String name = in.next();
            Student s = new Student();   
            studentList.add(s);

Try with :

        String name = in.next();
        Student s = new Student();   
        s.setName(name);
        studentList.add(s);

Also replace your constructor. Ie :

public StudentData(String name){
        setName(name);
}

should be

public Student(String name) {
        setName(name);
}

Then you will be able to do Student s = new Student(name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM