1

In below code have two methods scanner1 and scanner2 in both methods new object of Scanner is created and scanning the input after that closing the Scanner by invoking close().

import java.util.Scanner;

public class TestScanner {

    public static void scanner1(){
        Scanner sc = new Scanner(System.in);//created object of scanner
        System.out.println("Enter string :");
        String input = sc.nextLine(); //scanning input
        sc.close(); //closing scanner object
    }

    public static void scanner2(){//problem in scanner2
        Scanner sc = new Scanner(System.in);//created another scanner object
        System.out.println("Enter String :");
        String input = sc.nextLine();//scanning object
        sc.close();//closing the input
    }


    public static void main(String[] args) {
        scanner1();
        scanner2();//problem here

    }

}

For scanner1 method working fine but when scanner2 method get invoked getting the below error:

Enter string : India Exception in thread "main"

java.util.NoSuchElementException: No line found Enter String : at java.util.Scanner.nextLine(Unknown Source) at cheggapril.TestScanner.scanner2(TestScanner.java:17) at cheggapril.TestScanner.main(TestScanner.java:24)

Problem is why in scanner2 method scanner not able to scan the user input even in this method creating fresh one object of Scanner. Please give some clear explanation. any ref or example will be much greatful.

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
Roushan
  • 3,046
  • 3
  • 15
  • 31
  • http://stackoverflow.com/questions/14142853/close-a-scanner-linked-to-system-in –  Apr 29 '17 at 18:39
  • > The answer is simple you have created two scanner method but the > variable used to instantiate the scanner object have common name i.e. > "sc". **Solution :-** > Replace the name of sc in scanner two to some other name like.. public static void scanner2(){//problem in scanner2 Scanner sc2 = new Scanner(System.in);//created another scanner object System.out.println("Enter String :"); String input = sc.nextLine();//scanning object sc.close();//closing the input } – Amit Gujarathi Apr 29 '17 at 18:45

1 Answers1

1

The reason is quite simple, closing the 1st scanner object closes internally too the input stream which is actually being used by the second scanner

your options are: use only one scanner or close those when you are sure all of them are not required anymore..

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83