Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading