In the following program, a Scanner object closed and once it closed a System stream cannot be re-opened. Hence, after entered string, the control directly printed the default value of int n=0.
GD.java
importjava.util.Scanner;classGD{publicvoidaction(){stringScanner();intScanner();}publicvoidstringScanner(){Strings="";Scannersc=newScanner(System.in);System.out.print("Enter the string ");if(sc.hasNext()){s=sc.nextLine();}sc.close();System.out.println("\nString "+s);}publicvoidintScanner(){intn=0;Scannersc=newScanner(System.in);System.out.print("\nEnter the number ");if(sc.hasNext()){n=sc.nextInt();}sc.close();System.out.println("\nNumber "+n);}publicstaticvoidmain(Stringargs[]){System.out.println("———————————————————————————————————————————");System.out.println("Java implementation of Scanner close method");System.out.println("———————————————————————————————————————————");GDg=newGD();g.stringScanner();g.intScanner();System.out.println("———————————————————————————————————————————");}}
Output
godarda@gd:~$ javac GD.java godarda@gd:~$ java GD
———————————————————————————————————————————
Java implementation of Scanner close method
———————————————————————————————————————————
Enter the string GODARDA
String GODARDA
Enter the number
Number 0
———————————————————————————————————————————
godarda@gd:~$
Example 2: Java implementation of Scanner close method
Dear User, Thank you for visitng GoDarda. If you are interested in technical
articles, latest technologies, and our journey further, please follow us on LinkedIn.