Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Creating the MVP Remaining Tries

"Resource Leak Scanner is Never closed"

Hey, everyone. I'm working on this Hangman game in my local computer and in this function

public boolean promptForGuess() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a letter: ");
        String guessInput = scanner.nextLine();
        char guess = guessInput.charAt(0);

        // asks to do scanner.close()

        return game.applyGuess(guess);
    }

VS code highlights scanner and displays this message "Resource leak: 'scanner' is never close".

The thing is that, when I use scanner.close() at the end of the method, when I enter my second guess, it always raises an error: java.util.NoSuchElementException: No line found

The code only works when it's done like Craig did, not closing the scanner.

I would really appreciate if someone could help me on this. Thank you!

1 Answer

Steven Parker
Steven Parker
231,275 Points

It sounds like VSCode may be more stringent about resource management than the workspace. But I had an idea:

What if you made your "scanner" object global, created the new instance at the start of the "main" module, and then closed it right before that module ends?