0

I am 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 understand why this is so, so if anyone could advise/help me that would be great.

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;
        }
    }
2
  • Because student names are not initialised. This is reason why your values are null. Commented Dec 2, 2013 at 22:41
  • 1
    This shouldn't compile...You defined your class as Student but have a constructor defined as public StudentData(String name)... Commented Dec 2, 2013 at 22:43

1 Answer 1

4

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. I.e :

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.