Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

using hasNextLine() but still getting java.util.NoSuchElementException: No line found

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)

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);
  }
 }

Associated text file

John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are reading two lines while only checking for the existence of one

Here is the second read

String telno = read.nextLine(); //ArrayPhoneDirectory Line 42

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...