Pikachu
Pikachu

Reputation: 19

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)

Upvotes: 0

Views: 2146

Answers (3)

Just do a scanner.clear() at the end of procedures or before use it again.

Upvotes: 0

Vayun
Vayun

Reputation: 123

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.

Upvotes: 2

Ashish Patel
Ashish Patel

Reputation: 31

NoSuchElementException will be thrown because you are trying to read the data from the input (Scanner) where data is reached to the end.

You have to read the input( Scanner ) by checking hasNext() is true or false

Upvotes: 0

Related Questions