簡體   English   中英

java.util.NoSuchElementException錯誤

[英]java.util.NoSuchElementException Error

我嘗試從文本文件中讀取整行,並以不同的方式顯示它們。 例如,

    123456J;Gabriel;12/12/1994;67;67;89;

但是控制台中的結果將是:

    123456J Gabriel 72(which is average of three numbers)

這是我的代碼:

    public class Student{

String adminNo;
String name;
GregorianCalendar birthDate;
int test1,test2,test3;

public Student(String adminNo,String name,String birthDate,int test1, int test2, int test3){
    this.adminNo = adminNo;
    this.name = name;
    this.birthDate = MyCalendar.convertDate(birthDate);
    this.test1 = test1;
    this.test2 = test2;
    this.test3 = test3;
}

public Student(String studentRecord){
    String strBirthDate;
    Scanner sc = new Scanner(studentRecord);
    sc.useDelimiter(";");
    adminNo = sc.next();
    name = sc.next();
    strBirthDate = sc.next();
    birthDate = MyCalendar.convertDate(strBirthDate.toString());
    test1 = sc.nextInt();
    test2 = sc.nextInt();
    test3 = sc.nextInt();
}

public int getAverage(){ 
    return (( test1 + test2 + test3 ) / 3 ) ;
}

public String toString(){
    return (adminNo + " " + name + " " + getAverage());
}

public static void main(String [] args){

    Student s = new Student ("121212A", "Tan Ah Bee", "12/12/92", 67, 72, 79);
    System.out.println(s);

    String fileName = "student.txt";
    try{
        FileReader fr = new FileReader(fileName);
        Scanner sc = new Scanner(fr);

        while(sc.hasNextLine()){
            Student stud = new Student(sc.nextLine());
            System.out.println(stud.toString());
        }

        fr.close();
    }catch(FileNotFoundException exception){
        System.out.println("File " + fileName + " was not found");
    }catch(IOException exception){
        System.out.println(exception);
    }
}

和錯誤:

    Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Student.<init>(Student.java:24)
at Student.main(Student.java:52)

但是我收到java.util.NoSuchElementException錯誤。 我想念什么嗎? 它現在可以工作,但是突然出現錯誤。 我不知道為什么。

任何幫助,將不勝感激,謝謝。

您可以將Student構造函數修改為如下所示,以檢查發生異常時的行。

public Student(String studentRecord){
    String strBirthDate;
    Scanner sc = new Scanner(studentRecord);
    sc.useDelimiter(";");

    try {
         adminNo = sc.next();
         name = sc.next();
         strBirthDate = sc.next();
         birthDate = MyCalendar.convertDate(strBirthDate.toString());
         test1 = sc.nextInt();
         test2 = sc.nextInt();
         test3 = sc.nextInt();
    } catch (NoSuchElementException exception)
        System.out.println("NoSuchElementException, the line was: " + studentRecord);
    }
}

在掃描儀上調用next ...()之前,請確保掃描儀實際上具有該元素以避免該異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM