Java implementation of Scanner close method
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
import java.util.Scanner;
class KW
{
    public void action()
    {
        stringScanner();
        intScanner();
    }
    
    public void stringScanner()
    {
        String s="";
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter the string ");
        if(sc.hasNext())
        {
            s=sc.nextLine();
        }
        sc.close();
        System.out.println("\nString "+s);
    }
    
    public void intScanner()
    {
        int n=0;
        Scanner sc=new Scanner(System.in);
        System.out.print("\nEnter the number ");
        if(sc.hasNext())
        {
            n=sc.nextInt();
        }
        sc.close();
        System.out.println("\nNumber "+n);
    }
    
    public static void main(String args[])
    {
        System.out.println("———————————————————————————————————————————");
        System.out.println("Java implementation of Scanner close method");
        System.out.println("———————————————————————————————————————————");
        KW k=new KW();
        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
KW.java
import java.util.Scanner;
class KW
{
    public static void main(String args[])
    {
        String s="Hello, World!";
        Scanner sc=new Scanner(s);
        System.out.print(sc.nextLine());
        sc.close();
        System.out.println("\n\nScanner closed");     
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Hello, World! Scanner closed kodingwindow@kw:~$
Advertisement