我是java的新手,正在做一些arraylist工作,并且在编译列表时仅返回空值而不是我输入的名称。
我不明白为什么会这样,所以如果有人可以提供建议/帮助我,那将很棒。
提前致谢。
这是我的主要代码
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());
}
}
}
和
class Student
{
private String studentName;
public StudentData(String name)
{
setName(name);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
}
最佳答案
您正在创建一个学生,但未设置名称:
String name = in.next();
Student s = new Student();
studentList.add(s);
尝试:
String name = in.next();
Student s = new Student();
s.setName(name);
studentList.add(s);
同时替换您的构造函数。即:
public StudentData(String name){
setName(name);
}
应该
public Student(String name) {
setName(name);
}
这样您就可以执行
Student s = new Student(name);