1

I am using Scanner in my Java program and the Code works. However, I get warnings in my IDE (Eclipse Mars) whenever I use ".useLocale(Locale.US)". Code snippet:

Scanner factor1Input = new Scanner(System.in).useLocale(Locale.US);

double factor1 = factor1Input.nextDouble();

factor1Input.close();

The code can be compiled, executed and works, however, I get following warning in the IDE:

Warning:

Resource leak: <'unassigned Closeable value'> is never closed

All the Scanners that don't use "useLocale" are closed without any warning and the IDE as well as the Compiler do not complain about them.

Best regards and thank you in advance,

Coni

PS: further tag suggestions I could not add due to required reputation points: "scanner", "uselocale"

Coni Cool
  • 11
  • 2

1 Answers1

0

Option 1: Show eclipse you do close any opened scanner...

You can use a try-with-resources or close the scanner in a finally block.

try-with-resources

try (Scanner scanner = new Scanner(System.in); //
     Scanner factor1Input = scanner.useLocale(Locale.US)) {
   double factor1 = factor1Input.nextDouble();
   // ...
}

finally block

Scanner scanner=null;
Scanner factor1Input=null;

try {
    scanner = new Scanner(System.in);
    factor1Input = scanner.useLocale(Locale.US);

    double factor1 = factor1Input.nextDouble();

    // ...
} finally {
   if (factor1Input != null) {
       factor1Input.close();
   }

   if (scanner != null) {
       scanner.close();
   }
}

Option 2: Suppress the warning

 try (@SuppressWarnings("resource")
 Scanner factor1Input = new Scanner(System.in).useLocale(Locale.US)) {
     double factor1 = factor1Input.nextDouble();
     // ...
 }
Stephan
  • 41,764
  • 65
  • 238
  • 329