0

我正在测试我的大学班级,当用户输入“添加”时,它会在大学班级的数组列表中添加一个新学生。

   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 方法在 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 是一个长字符串而不是字符串我该怎么办?

4

3 回答 3

2

没有必要在读取后拆分字符串。您可以使用扫描仪读取分隔字符串。

我假设您的输入由空格分隔。如果是这样,您需要这样做:

    String name = myInput.next();
    long id = myInput.nextLong();
    String address = myInput.next();
    dictionary.add(name, id, address);
于 2013-10-01T03:27:20.427 回答
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;
    }
}
于 2013-10-01T03:39:21.280 回答
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()方法的参数转换值

于 2013-10-01T03:42:45.523 回答