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.
KW.java
importjava.util.Scanner;classKW{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("———————————————————————————————————————————");KWk=newKW();k.stringScanner();k.intScanner();System.out.println("———————————————————————————————————————————");}}
Output
kodingwindow@kw:~$ javac KW.java kodingwindow@kw:~$ java KW
———————————————————————————————————————————
Java implementation of Scanner close method
———————————————————————————————————————————
Enter the string KODINGWINDOW
String KODINGWINDOW
Enter the number
Number 0
———————————————————————————————————————————
kodingwindow@kw:~$
Example 2: Java implementation of Scanner close method
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.
Dear User, We are grateful for your interest in the KodingWindow Android app. We intend to soon make it available on the Google Play Store. Currently, you need to install apk manually. Would you like to get the app? Minimum Requirement(s): Android 10