Issue
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;
}
}
Solution
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);
Answered By - user2336315
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.