Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner is never closed

I'm working on a game and I came across a little problem with my scanner. I'm getting a resource leak scanner never closed.

But I thought my scanner was working before without closing it. But now it ain't. Anyone can help me out here?

import java.util.Scanner;  public class Main {      public static final boolean CHEAT = true;      public static void main(String[] args) {          Scanner scanner = new Scanner(System.in);         int amountOfPlayers;         do {             System.out.print("Select the amount of players (1/2): ");             while (!scanner.hasNextInt()) {                 System.out.println("That's not a number!");                 scanner.next(); // this is important!         }          amountOfPlayers = scanner.nextInt();         while ((amountOfPlayers <= 0) || (amountOfPlayers > 2));         System.out.println("You've selected " + amountOfPlayers+" player(s).");      } } 
like image 413
Niek van der Linden Avatar asked Mar 25 '13 11:03

Niek van der Linden


People also ask

What happens if scanner is not closed?

If you do not close the scanner class it will generate warnings like Resource leak. Resource leak happens when a program doesn't release the resources it has acquired. As OS have limit on the no of sockets,file handle,database conn etc thus its extremely important to manage these non-memory resources explicitly.

Does a scanner have to be closed?

If you do not close the Scanner then Java will not garbage collect the Scanner object and you will have a memory leak in your program: void close(): closes the Scanner and allows Java to reclaim the Scanner's memory. You cannot re-use a Scanner so you should get rid of it as soon as you exhaust its input.

How do you close a scanner function?

close() method closes this scanner. If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked.

Why does scanner need to be closed?

It is recommended to always close the Scanner when we are reading a file. It ensures that no input or output stream is opened, which is not in use. The following example shows how we can read a string from the file and then close the scanner once the operation has been done.


1 Answers

I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.

Scanner scanner = null; try {     scanner = new Scanner(System.in);     //rest of the code } finally {     if(scanner!=null)         scanner.close(); } 

Or even better: use the new Try with resource statement:

try(Scanner scanner = new Scanner(System.in)){     //rest of your code } 
like image 107
PermGenError Avatar answered Sep 21 '22 14:09

PermGenError