58

I got an run time exception in my program while I am reading a file through a Scanner.

java.util.NoSuchElementException: No line found     
   at java.util.Scanner.nextLine(Unknown Source)    
   at Day1.ReadFile.read(ReadFile.java:49)  
   at Day1.ParseTree.main(ParseTree.java:17) 

My code is:

while((str=sc.nextLine())!=null){
    i=0;
    if(str.equals("Locations"))
    {
        size=4;
        t=3;
        str=sc.nextLine();
        str=sc.nextLine();
    }
    if(str.equals("Professions"))
    {
        size=3;
        t=2;
        str=sc.nextLine();
        str=sc.nextLine();
    }
    if(str.equals("Individuals"))
    {
        size=4;
        t=4;
        str=sc.nextLine();
        str=sc.nextLine();
    }

int j=0;
String loc[]=new String[size];
while(j<size){
    beg=0;
    end=str.indexOf(',');
    if(end!=-1){
        tmp=str.substring(beg, end);
        beg=end+2;
    }
    if(end==-1)
    {
        tmp=str.substring(beg);
    }
    if(beg<str.length())
        str=str.substring(beg);
    loc[i]=tmp;
    i++;

    if(i==size ){
        if(t==3)
        {
            location.add(loc);
        }
        if(t==2)
        {
            profession.add(loc);
        }
        if(t==4)
        {
            individual.add(loc);
        }
        i=0;
    }
    j++;
    System.out.print("\n");
}
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Ashish Panery
  • 1,196
  • 3
  • 13
  • 24
  • 10
    Welcome to SO. When posting code you should take care to format it for readability... i.e. remove unnecessary blank lines, indent properly. Also format your stacktrace as code to make it readable. I fixed the formatting for you. – Jim Garrison Aug 26 '11 at 18:44
  • 9
    Also, you left out the most important piece, which is how `sc` was declared and opened. – Jim Garrison Aug 26 '11 at 18:45

7 Answers7

53

with Scanner you need to check if there is a next line with hasNextLine()

so the loop becomes

while(sc.hasNextLine()){
    str=sc.nextLine();
    //...
}

it's readers that return null on EOF

ofcourse in this piece of code this is dependent on whether the input is properly formatted

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
22

I also encounter with that problem. In my case the problem was that I closed the Scanner inside one of the funcs..

public class Main 
{
    public static void main(String[] args) 
    {
        Scanner menu = new Scanner(System.in);
        boolean exit = new Boolean(false);
        while(!exit) {
            String choose = menu.nextLine();
            Part1 t=new Part1()
            t.start();
            System.out.println("Noooooo Come back!!!"+choose);
        }
        menu.close();
    }
}

public class Part1 extends Thread 
{
    public void run()
    { 
        Scanner s = new Scanner(System.in);
        String st = s.nextLine();
        System.out.print("bllaaaaaaa\n" + st);
        s.close();
    }
}

The code above made the same exeption, the solution was to close the scanner only once at the main.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
agr
  • 221
  • 2
  • 2
  • Thanks for that buddy, stuck on this tiny mistake – AWGAL Nov 04 '19 at 11:19
  • 7
    I have the similar problem. I want to know why it wont work if I close the scanner and re-initialise it again when I read next line. They should both be different instances of scanner right? Why would closing one instance of scanner affect the other one? – Kaushik Evani Nov 13 '19 at 16:39
  • https://stackoverflow.com/questions/33555283/why-is-not-possible-to-reopen-a-closed-standard-stream – semaphore Dec 06 '22 at 12:18
18

You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Alexandros Kourtis
  • 539
  • 2
  • 6
  • 20
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
8

For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine() method before each call to nextLine(), make sure the correct encoding is passed to the Scanner constructor, e.g.:

Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");

Luís de Sousa
  • 5,765
  • 11
  • 49
  • 86
8

Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.

For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.

Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called

      "java.util.NoSuchElementException: No line found".

If you have to call "sc.nextLine()" n times, then you have to have at least n lines.

Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.

William Hou
  • 1,251
  • 14
  • 17
0

Need to use top comment but also pay attention to nextLine(). To eliminate this error only call

sc.nextLine()

Once from inside your while loop

 while (sc.hasNextLine()) {sc.nextLine()...}

You are using while to look ahead only 1 line. Then using sc.nextLine() to read 2 lines ahead of the single line you asked the while loop to look ahead.

Also change the multiple IF statements to IF, ELSE to avoid reading more than one line also.

0

I ran into this problem, my structure was: 1 - System 2 - Registration <-> 3 - validate

I was closing Scanner on each of the 3 steps. I started to close the Scanner only in system and it solved.

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 06 '22 at 03:33