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.
Codeaft.java
importjava.util.Scanner;classCodeaft{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("———————————————————————————————————————————");Codeaftc=newCodeaft();c.stringScanner();c.intScanner();System.out.println("———————————————————————————————————————————");}}
Output
codeaft@codeaft:~$ javac Codeaft.java codeaft@codeaft:~$ java Codeaft
———————————————————————————————————————————
Java implementation of Scanner close method
———————————————————————————————————————————
Enter the string CODEAFT
String CODEAFT
Enter the number
Number 0
———————————————————————————————————————————
codeaft@codeaft:~$
Example 2: Java implementation of Scanner close method
Dear User, Thank you for visitng Codeaft. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.