Search code examples
javatry-catchjava.util.scannertry-catch-finally

scanner.close() Does not work when I use try/finally


import java.util.Scanner;
public class userInput
{
    public static void main(String[]args){

        try{
            Scanner scanner = new Scanner(System.in);
        
        
            String name = scanner.nextLine();
            int age = scanner.nextInt(); 
            scanner.nextLine();
            String text = scanner.nextLine();
        
            System.out.println(name + "\n" + age + "\n" + text);
            //scanner.close(); //it works here
        } 
    
        finally{
            scanner.close(); // does not work here"scanner cannot be resolvedJava(570425394)"
        }
    }
}

Solution

  • You have to define scanner before "try", so it's ok, now this is your code:

    import java.util.Scanner;
    
    public class userInput { 
    
        public static void main(String[]args) {
            Scanner scanner = new Scanner(System.in);
            try {
                 String name = scanner.nextLine();
                 int age = scanner.nextInt(); 
                 scanner.nextLine();
                 String text = scanner.nextLine();
    
                 System.out.println(name + "\n" + age + "\n" + text);
            } 
    
            finally {
                 scanner.close();
            }
        }
    }