我正在测试我的大学课程,当用户输入“添加”时,它会向大学班级的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);
这里的目录是包含学生的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是一个长而不是字符串我该怎么办?
答案 0 :(得分:2)
无需在阅读后拆分字符串。您可以使用Scanner读取分隔的字符串。
我假设您的输入由空格分隔。如果是这样,您需要这样做:
String name = myInput.next();
long id = myInput.nextLong();
String address = myInput.next();
dictionary.add(name, id, address);
答案 1 :(得分: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;
}
}
答案 2 :(得分:0)
您可以使用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]
所以你可以通过addStudent()
方法轻松传递。但您需要根据addStudent()
方法