Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchElement using scanner

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

After this when i am closing the Scanner and again reading the another input using the Scanner,then it throws an error: NoSuchElementException. Please guide me on 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);
  }

}
like image 418
Vivek Avatar asked Jan 24 '26 10:01

Vivek


1 Answers

When you close your scanner it also closes System.in input stream, you are using it again, but it's closed, so when you try to use Scanner again, no open System.in stream is found.

like image 51
Maroun Avatar answered Jan 25 '26 23:01

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!