Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.NoSuchElementException: No line found

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"); } 
like image 655
Ashish Panery Avatar asked Aug 26 '11 18:08

Ashish Panery


People also ask

How do I resolve Java Util NoSuchElementException in Java?

Solution. The solution to this​ exception is to check whether the next position of an iterable is filled or empty. You should only move to this position if the check returns that the position is not empty.

How do I avoid Java Util NoSuchElementException?

NoSuchElementException in Java can come while using Iterator or Enumeration or StringTokenizer. Best way to fix NoSuchElementException in java is to avoid it by checking Iterator with hashNext(), Enumeration with hashMoreElements() and StringTokenizer with hashMoreTokens().

Does Java have nextLine?

The hasNextLine() is a method of Java Scanner class which is used to check if there is another line in the input of this scanner. It returns true if it finds another line, otherwise returns false.


2 Answers

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

like image 102
ratchet freak Avatar answered Sep 28 '22 06:09

ratchet freak


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

like image 37
Brian Roach Avatar answered Sep 28 '22 05:09

Brian Roach