我正在尝试使用 ArrayList 根据用户输入创建一个应用程序。但有一个问题我需要先了解一下。
PS:我想在进入用户输入之前先尝试使用正常值。这只是一个粗略的草图,让我了解如何在数组列表中使用多个参数。
这是学生
package test;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Student {
private String name;
private Date DOB;
private String[] friend;
private String school;
public Student(String name, Date DOB, String[] friend, String school) {
this.name = name;
this.DOB = DOB;
this.friend = friend;
this.school = school;
}
public void display() {
System.out.println("Name : " + name);
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
System.out.println("Released Date : " + df.format(DOB));
System.out.println("Best Friend : " + friend[0] + ", " + friend[1]);
System.out.println("Director : " + school);
}
public String getName() {
return name;
}
}
这是学生应用程序
package test;
import java.util.ArrayList;
public class StudentApp {
private ArrayList<Student> students = new ArrayList<Student>();
public void start() {
addStudent();
}
public void addStudent() {
System.out.println("- Add Student Info -");
students.add(/* Need to ask the user to input their information like their name,DOB,friend,school*/);
}
}
如果需要多个参数,如何将值添加到数组列表中? (字符串、日期、字符串[]、字符串)。因为当我尝试将一些值与所需的正确参数添加到 Students.add 中时,它会显示一条错误消息
The method add(int, Student) in the type ArrayList is not applicable for the arguments (String, null, String, String)
最佳答案
您想要做的是在列表中添加错误的元素。
您的学生
列表是学生
列表。正如前面指出的,students.add()
只接受 Student
类型的对象。
您必须执行以下操作:
System.out.println("- Add Student Info -");
String name = ""; //Get name from user
Date dob = new Date(); //Get DOB from user
String[] friends = new String[]{"Friend1", "Friend2"}; //Get a list of friends from user
String school = ""; //Get school from user
students.add(new Student(name, dob, friends, school));
//OR students.add(0, new Student(name, dob, friends, school)); //Replace 0 with any index
关于java - 具有多个参数的ArrayList(用户输入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21201922/