NoSuchElement using a scanner

I have declared two strings and reading the input using Scanner(System.in).

      

After that, when I close the scanner and read another input again with the scanner, it throws an error: NoSuchElementException . Please help me with this

import java.util.Scanner;
import java.io.*;  

public class NumericInput

{
  public static void main(String[] args)
  {
    // Declarations
    Scanner in = new Scanner(System.in);
    String string1;
    String string2;

   // Prompts 
    System.out.println("Enter the value of the First String .");
   // Read in values  
    string1 = in.nextLine();
    // When i am commenting below line(in.close) code is working properly. 
    in.close();
    Scanner sc = new Scanner(System.in);
    System.out.println("Now enter another value.");
    string2 = sc.next();
    sc.close();

    System.out.println("Here is what you entered: ");
    System.out.println(string1 + " and " + string2);
  }

}

      

+3


source to share


2 answers


When you close

your scanner it also closes System.in

, you use it again, but it is closed, so when you try to use it again Scanner

, the open stream is System.in

not found.



+4


source


There is no need to close the scanner, as it implements the AutoCloseable interface, you must declare resources in try-with-resources with java 7. If closing the scanner is a problem.



try(Scanner in = new Scanner(System.in); Scanner sc = new Scanner(System.in)){
 // do stuff here without closing
}

 catch(Exception){
  e.printStackTrace();
 }

      

0


source







All Articles