0

私がやろうとしているのは、テキストファイルから情報を取得することです。

      For example, 134567H;Gabriel;24/12/1994;67;78;89

次に、ドロップダウンリストの行全体ではなく、最初の管理者番号のみを表示します。だからここに私のコードがあります:

    public static String[] readFile(){
    String file = "output.txt";
    ArrayList <String> studentList = new ArrayList <String> ();
    try{
    FileReader fr = new FileReader(file);
    Scanner sc = new Scanner(fr);
    sc.useDelimiter(";");

    while(sc.hasNextLine()){
        studentList.add(sc.nextLine());
    }

    fr.close();
    }catch(FileNotFoundException exception){
        System.out.println("File " + file + " was not found");
    }catch(IOException exception){
        System.out.println(exception);
    }
    return studentList.toArray(new String[studentList.size()]);
}

そして、これがドロップダウンリストに入力する方法です:

    public void populate() {
    String [] studentList ;
    studentList = Question3ReadFile.readFile();

    jComboBox_adminNo.removeAllItems();

    for (String str : studentList) {
       jComboBox_adminNo.addItem(str);
    }
}

しかし、私の問題は、ドロップダウンリストのオプションがテキストファイルの行全体を表示していることです。管理者番号のみを表示しているわけではありません。私はすでにuseDelimiterで試しました。私はそれを使うべきですか?

どんな助けでも大歓迎です。前もって感謝します。

リンスヘルプチェック。

    public class Question3ReadFile extends Question3 {

private String adminNo;

public Question3ReadFile(String data) {
    String[] tokens = data.split(";");
    this.adminNo = tokens[0];
}

public static String[] readFile(){
    String file = "output.txt";
    ArrayList <String> studentList = new ArrayList <String> ();
    try{
    FileReader fr = new FileReader(file);
    Scanner sc = new Scanner(fr);

    while(sc.hasNextLine()){
        studentList.add(new Question3ReadFile(sc.nextLine()));
    }

    fr.close();
    }catch(FileNotFoundException exception){
        System.out.println("File " + file + " was not found");
    }catch(IOException exception){
        System.out.println(exception);
    }
    return studentList.toArray(new String[studentList.size()]);
}
4

2 に答える 2

1

この場合、区切り記号は使用しないでください。Student オブジェクトを作成することをお勧めします。

studentList.add(new Student(sc.nextLine));

そして学生クラスを持っています:

public class Student {
    private final String adminNo;

    public Student(String data) {
        String[] tokens = data.split(";");
        this.adminNo = tokens[0];
    }


    public String getAdminNo() {
        return adminNo;
    }
}

後で必要なフィールドを読み取るだけです (student.getAdminNo())。

このアプローチは、後で拡張するのがはるかにきれいで簡単です。

更新:単純なアプローチ

または、愚かな OO を気にせずに、次のようにします。

studentList.add(sc.nextLine.split(";")[0]);
于 2013-04-18T12:27:50.367 に答える