使用hasNextLine()但仍然得到java.util.NoSuchElementException:找不到行 [英] using hasNextLine() but still getting java.util.NoSuchElementException: No line found

查看:116
本文介绍了使用hasNextLine()但仍然得到java.util.NoSuchElementException:找不到行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个编程项目并继续收到下面显示的错误。

I'm doing a programming project and keep getting the error shown below.

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1585)
    at ArrayPhoneDirectory.loadData(ArrayPhoneDirectory.java:42)
    at ArrayPhoneDirectoryTester.main(ArrayPhoneDirectoryTester.java:18)

我认为这是因为扫描仪read.nextLine()正在进行中超过文本文件的结尾。但是我使用了带有hasNextLine的while循环,所以我不确定为什么会这样。
任何人都知道我哪里出错?

I thought this would be because the scanner read.nextLine() is going past the end of the text file. But I've used a while loop with hasNextLine so I'm not sure why this is happening. Anyone know where I'm going wrong?

 public void loadData (String sourceName){
Scanner read = new Scanner(sourceName);

while (read.hasNextLine()) {
    String name = read.nextLine();
    String telno = read.nextLine(); //ArrayPhoneDirectory Line 42
    add(name, telno);
  }
 }

相关文本文件

John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231


推荐答案

hasNextLine()

将只检查一个新行。检查一个后,你不能读两行。

will check only for one new line. you cannot read two lines after checking for just one.

如果你必须连续阅读记录,那么你可以做

If you have to continuously read records then you could do

public void loadData (String sourceName){
    Scanner read = new Scanner(sourceName);
    int i = 1;

    while (read.hasNextLine()) {
        if(i%2 != 0)
            String name = read.nextLine();
        else
            String telno = read.nextLine(); //ArrayPhoneDirectory Line 42
        add(name, telno);
        i++;
    }
}

这篇关于使用hasNextLine()但仍然得到java.util.NoSuchElementException:找不到行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆