簡體   English   中英

掃描儀-忽略文件末尾的新行

[英]Scanner - Ignore new line at end of file

進入/忽略文件reg.txt中的最后一行時,我需要退出方面的幫助。 截至目前,當它到達最后一行時不顯示任何錯誤。

public String load() {
        list.removeAllElements();
        try {
            Scanner scanner = new Scanner(new File("reg.txt"));

            while (scanner.hasNextLine()) {
                String lastname = scanner.next();
                String firstname = scanner.next();
                String number = scanner.next();
                list.add(new Entry(firstname, lastname, number));
            }
            msg = "The file reg.txt has been opened";
            return msg;
        } catch (NumberFormatException ne) {
            msg = ("Can't find reg.txt");
            return msg;
        } catch (IOException ie) {
            msg = ("Can't find reg.txt");
            return msg;
        }
    }

reg.txt示例:

Allegrettho     Albert          0111-27543
Brio            Britta          0113-45771
Cresendo        Crister         0111-27440

我應該如何編輯掃描儀的讀數,以便忽略文件末尾的新行?

在循環結束時,執行

Scanner.nextLine();

一種干燥而骯臟的方法是在每一個scan.next()之前檢查是否有下一行。

if(scanner.hasNextLine())
{
  lastname = scanner.next();
}

或在字符串姓氏之后:

if(!lastname.isEmpty())
{
   //continue here...
}

您可以為Entry參數添加一個驗證,如果有空行,您將跳過它。

if(firstname != null || lastname != null || number != null) {
    list.add(new Entry(firstname, lastname, number));
}

最簡單的方法可能是將數據集合包含在if語句中,以檢查scanner.next()是否不為空:

while (scanner.hasNextLine()) {
    if(!scanner.next().equals("")&&!scanner.next()==null){
        String lastname = scanner.next();
        String firstname = scanner.next();
        String number = scanner.next();
        list.add(new Entry(firstname, lastname, number));
    }
}

否則,我會看看您的hasNextLine方法,以了解當下一行為空時說“是的,我有下一行”的邏輯;)

與其使用next()讀取最后一個字段, nextLine()使用nextLine() 這將使掃描儀前進到行尾,但不會在結果中返回行尾字符。

scanner.hasNextLine()將為false ,因此循環不會再次開始。

while (scanner.hasNextLine()) {
    String lastname = scanner.next();
    String firstname = scanner.next();
    String number = scanner.nextLine();
    list.add(new Entry(firstname, lastname, number));
}

暫無
暫無

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

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