Search code examples
javanosuchelementexception

NoSuchElementException in java.util.Scanner


This code was compiled successfully but it is showing runtime error and exception as no such element in scanner class. After reading the testcase, it should take the input as string, but it is showing anexception.

public class CandidateCode 
{
      public static void main(String args[] ) throws Exception
      {
            //Write code here
            Scanner sc=new Scanner(System.in);
            int testCase=sc.nextInt();
            while(testCase>0)
            {
                     //sc.next();
                     Scanner scan=new Scanner(System.in);
                     String temp="";
                     String res="";
                     for(int i=0;i<str.length();i++)
                     {
                        if(temp.indexOf(str.charAt(i))==-1)
                           temp=temp+str.charAt(i);
                        else
                        {
                           res=res+str.charAt(i);
                         }
                      }
                      char min='z';
                      for(int j=0;j<res.length();j++)
                      {
                         if(res.charAt(j)<min)
                            min=res.charAt(j);
                      }
                      System.out.println(min);
                      testCase++;
              }
      }
  }

The compilation log error is:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at CandidateCode.main(CandidateCode.java:19)


Solution

  • NoSuchElementException is thrown from Scanner.next() if you are trying to read data when you have reached the end of the data stream.

    Instead of:

    sc.next();
    ...
    

    use:

    while(! sc.hasNext()) { }
    sc.next();
    ...
    

    Scanner.hasNext() checks if there is any more data to read, and the while loop waits until there is more data to read before continuing.