簡體   English   中英

沒有這種元素異常掃描器

[英]no such element exception scanner

Scanner s = new Scanner(new File("src/mail_list"));    
while (s.hasNextLine()){
        String line1 = s.nextLine();
        if (line1.startsWith("Users")){
            line1 = s.nextLine();
            while (!(line1 = s.nextLine()).isEmpty()) {
                String arr[] = line1.split(" ", 4);
                users.add(new User(arr[0],arr[1],arr[2],arr[3]));
            }
        }
        if (line1.startsWith("Lists")){
            line1 = s.nextLine();
            while (!(line1 = s.nextLine()).isEmpty()) { //exception here
                String arr1[] = line1.split(" ", 2);
                ArrayList<String> tmp = new ArrayList<String>();
                StringTokenizer st = new StringTokenizer(arr1[1]);
                while (st.hasMoreTokens()) {
                    tmp.add(st.nextToken());
                }
                list.add(new List((arr1[0]), tmp));
            }
        }
    }

/*-testfile-start*/
Keyword: Users
username1 Name1 Surname1 email1
username2 Name2 Surname2 email2

Keyword: Lists
list_name username1 username2 ...
/*-testfile-end*/

我正在使用上面的代碼來從上面的testfile模式中對事物進行排序。 基本上它意味着如果我遇到關鍵字“用戶”,我必須添加關於用戶的所述信息。

我在代碼中標記了異常上升的地方。 關於如何應對它的任何想法?

您正在調用nextLine()兩次,但只檢查hasNextLine()一次。

String line1 = s.nextLine();
    if (line1.startsWith("Users")){
        line1 = s.nextLine();

意思是你在不知道是否有一行的情況下獲得下一行,如果沒有,則拋出異常。

我找到了一個愚蠢的解決方案。 我剛剛在最后一行之后添加了一個'虛擬'字符2行。 它的工作原理。 這不是一個完美的解決方案,但由於測試文件不是任何人都可以看到的,我現在就把它拿走...感謝所有與我共謀45分鍾的人。

Do!(line1 = s.nextLine())!= null,不為空,因為它無法讀取空行。

來自Scanner#nextLine

拋出:
NoSuchElementException - 如果未找到任何行。

你有這個代碼:

while (s.hasNextLine()) {
    //checked if there's line to read
    String line1 = s.nextLine();
    if (line1.startsWith("Users")) {
        //not checked if there's line to read
        line1 = s.nextLine();
        //not checked here either
        while (!(line1 = s.nextLine()).isEmpty()) {
            String arr[] = line1.split(" ", 4);
            users.add(new User(arr[0],arr[1],arr[2],arr[3]));
        }
    }
    //similar in code below...
}

確保在使用Scanner#nextLine之前驗證是否有要讀取的行。 相應地處理異常。

在此輸入圖像描述

如您所見,此方法在未找到任何行時拋出NoSuchElementException。

if (line1.startsWith("Lists")){
        line1 = s.nextLine(); // <=============== ?
        while (!(line1 = s.nextLine()).isEmpty()) { //exception here

你怎么知道你的評論線上有更多的線?

暫無
暫無

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

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