2013-10-01 17 views
0

我正在測試我的大學課程,當用戶輸入「add」時,它將新學生添加到大學課堂中的數組列表中。使用Java將參數添加到arraylist中

Scanner myInput=new Scanner (System.in); 
    String information=myInput.next(); //I know this is incorrect not sure what else to do 
    directory.addStudent(information); 

這裏的目錄是包含學生的數組列表對象。傳遞addStudent方法是在大專班,看起來像這樣:

public void addStudent (String studentName, long studentID, String address) { 
     Student newStu= new Student(studentname, studentID, address); 
     collegeList.add(newStu); //here collegeList is the name of the arraylist in College class 
    } 

反正我的問題似乎很簡單,但不能弄明白。我想知道如何分割信息,以便它可以滿足addStudent方法中的參數......正如您所看到的信息將是一個字符串,但我希望studentID是一個長而不是字符串,我該怎麼辦?

+0

的參數轉換值請看一下各種'X.parseX()'方法,其中X是Number的常見子類型。 –

+0

提供有關您的輸入的一些信息。如何在輸入中分隔名稱,ID和地址?換行符?空白?逗號? – Mohayemin

回答

2

閱讀後拆分字符串是沒有必要的。您可以使用掃描儀閱讀分隔字符串。

我假設你的輸入被空格分開。如果是這樣,你需要做的是:

String name = myInput.next(); 
    long id = myInput.nextLong(); 
    String address = myInput.next(); 
    dictionary.add(name, id, address); 
0

試試這個:

import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 
public class StudentMain { 
    private static List<Student> collegeList = new ArrayList<Student>(); 
    public static void main(String...args)throws Throwable { 
     String s= null; String name=null; long id=0L; String address = null; 
     System.out.print("What do you want to do today, press q to quit : "); 
     Scanner sc = new Scanner(System.in); 
     do{ 
     try{  
       s = sc.next(); 
       if(s.equalsIgnoreCase("add")){ 
        System.out.print("Enter the name of student: "); 
        name = sc.next(); 
        System.out.print("Enter the Id of student : "); 
        id=sc.nextLong(); 
        System.out.print("Enter address of student: "); 
        address = sc.next(); 
        addStudent(name,id,address); 
       } 
     }catch(NumberFormatException e){ 
      if(!s.equalsIgnoreCase("q")) 
       System.out.println("Please enter q to quit else try again ==> "); 
      } 
     }while(!s.equalsIgnoreCase("q")); 
    sc.close(); 
    } 
    private static void addStudent(String name, long id, String address) { 
     // TODO Auto-generated method stub 
     Student newStu = new Student(name,id,address); 
     collegeList.add(newStu);   
    } 

} 

class Student{ 
    String name; 
    Long id; 
    String address; 

    Student(String name,Long id,String address){ 
    this.name= name; 
    this.id = id; 
    this.address=address; 
    } 
} 
0

您可以使用split()方法來打破你的信息

,你所要做的就是

String str = new String(information); 
String[] s = str.split(" ", 3); 

我在空間的基礎上分裂,第二個參數3意味着你必須分成3個字符串,即n艾美,身份證,地址

之後,你可以得到name via s[0] , id via s[1] and address via s[2] 所以你可以輕鬆地通過addStudent()方法。但您需要根據參數addStudent()方法