Home > Software design >  scanner.close() Does not work when I use try/finally
scanner.close() Does not work when I use try/finally

Time:04-12

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)"
        }
    }
}

CodePudding user response:

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();
        }
    }
}
  • Related