2014-01-18 126 views
0

我想創建一個基於ArrayList的用戶輸入的應用程序基礎。但有一些問題需要先了解。具有多個參數的ArrayList(用戶輸入)

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)。因爲當我嘗試添加所需要進入students.add正確的參數一定的價值,它會告訴我一個錯誤說

在ArrayList類型的方法Add(INT,學生)不 適用於參數(字符串,空,字符串,字符串)

回答

0

你所要做的是在列表中添加錯誤的元素。

名單你studentsStudent列表。正如前面指出的那樣,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 
1

您需要在您的ArrayList

students.add(new Student(String, String, String, String)) 
+0

我喜歡你如何張貼你的答案我之前9秒:-)。 – Justin

0

您不能添加多個參數添加Student類的對象到ArrayList,至少不是這種形式。它看起來像你真正想要做的是:

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)); 
相關問題