java - Scanner is never closed -


i'm working on game , came across little problem scanner. i'm getting resource leak scanner never closed.

but thought scanner working before without closing it. ain't. can 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;         {             system.out.print("select amount of players (1/2): ");             while (!scanner.hasnextint()) {                 system.out.println("that's not number!");                 scanner.next(); // important!         }          amountofplayers = scanner.nextint();         while ((amountofplayers <= 0) || (amountofplayers > 2));         system.out.println("you've selected " + amountofplayers+" player(s).");      } } 

i assuming using java 7, compiler warning, when don't close resource should close scanner in block.

scanner scanner = null; try {     scanner = new scanner(system.in);     //rest of code } {     if(scanner!=null)         scanner.close(); } 

or better: use new try resource statement:

try(scanner scanner = new scanner(system.in)){     //rest of code } 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -