具有多个参数的ArrayList(用户输入)

时间:2014-01-18 08:38:23

标签: java arraylist arguments

我正在尝试使用ArrayList创建一个基于用户输入的App。但是我首先需要了解一些问题。

PS:我想在进入用户输入之前先尝试正常值。这只是一个粗略的草图,让我了解如何在arraylist中使用多个参数。

这是学生

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

}

这是StudentApp

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*/);
    }

}

如果需要多个参数,如何将值添加到arraylist? (String,Date,String [],String)。因为当我尝试使用student.add中所需的正确参数添加一些值时,它会显示错误说

  

ArrayList类型中的方法add(int,Student)不是   适用于参数(String,null,String,String)

3 个答案:

答案 0 :(得分:1)

您需要在Student

中添加ArrayList课程的对象
students.add(new Student(String, String, String, String))

答案 1 :(得分:0)

您无法向ArrayList添加多个参数,至少不能以该形式添加。{p>看起来你真正想做的是:

students.add(new Student(/*whatever info*/));

如果您真的想要ArrayList中的多个元素,请执行以下操作:

ArrayList<Object[]> list = new ArrayList<>(); // or if you know all of them are Strings, String[]
list.add(new Object[]{arg1, arg2, arg3, arg4});

更好的是创建一个特殊的类,如:

class Data{
    private String[] data;

    public Data(String s1, String s2, String s3, String s4){
        data = {s1, s2, s3, s4};
    }

    public String getElement(int index){
        return data[index];
    }
}

然后,像这样使用它:

ArrayList<Data> list = new ArrayList<>();
list.add(new Data(arg1, arg2, arg3, arg4));

答案 2 :(得分:0)

您要做的是在列表中添加错误的元素。

students列表是Student的列表。正如前面所指出的,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