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 了。我应该用那个吗?

任何帮助,将不胜感激。提前致谢。

Rince帮助检查。

    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

2

hasNext 和 next 而不是 hasNextLine 和 nextLine

public static void main(String[] args) {
     String input = " For example, 134567H;Gabriel;24/12/1994;67;78;89";
     Scanner scanner = new Scanner(input);
     scanner.useDelimiter(";");
     String firstPart = null;
     while(scanner.hasNext()){
         firstPart = scanner.next();
         break;
     }

     String secondPart = input.split(firstPart)[1].substring(1);
     System.out.println(firstPart);
     System.out.println(secondPart);
     scanner.close();
}
于 2013-04-18T12:16:21.950 回答
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())。

这种方法更漂亮,以后更容易扩展。

upd:简单的方法

或者不要为愚蠢的OO而烦恼,只需这样做:

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