[英]Adding parameters to arraylist with Java
我正在測試我的大學課程,當用戶輸入“添加”時,它會在大學課堂中為新學生添加一名新學生。
Scanner myInput=new Scanner (System.in);
String information=myInput.next(); //I know this is incorrect not sure what else to do
directory.addStudent(information);
這里的目錄是包含學生的arraylist的對象。 addStudent方法在College類中,如下所示:
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是一個長而不是字符串我該怎么辦?
讀取后拆分字符串是沒有必要的。 您可以使用Scanner讀取分隔的字符串。
我假設您的輸入由空格分隔。 如果是這樣,您需要這樣做:
String name = myInput.next();
long id = myInput.nextLong();
String address = myInput.next();
dictionary.add(name, id, address);
嘗試這個:
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;
}
}
您可以使用split()
方法來破壞您的信息
你要做的是
String str = new String(information);
String[] s = str.split(" ", 3);
我在空間基礎上分裂,第二個參數3意味着你必須分成3個字符串,即名稱,ID,地址
在此之后,您可以name via s[0] , id via s[1] and address via s[2]
獲取name via s[0] , id via s[1] and address via s[2]
獲取name via s[0] , id via s[1] and address via s[2]
這樣您就可以輕松通過addStudent()
方法。 但您需要根據addStudent()
方法的參數轉換值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.