Search code examples
javaconsoleresource-leak

Java resource leak not closed


I am writing a program where I want the console to output the remainder of the user inputted number. However, every time I compile the code the console prints this out and I get this console error:

 1 problem (1 warning)
 Compiler is using classPath = '[C:\Users\Darien Springer\Documents\Java,   C:\Users\Darien Springer\Desktop\drjava-beta-20160913-225446.exe]';  bootClassPath = 'null'
 ----------
 1. WARNING in C:\Users\Darien Springer\Documents\Java\PrintDigits.java (at   line 5)
     Scanner scnr= new Scanner(System.in); 
        ^^^^
 Resource leak: 'scnr' is never closed
 ----------
 1 problem (1 warning)

I am not sure what the console means by a "resource leak". I have looked it up in several different places (including the API and other Stack Overflow questions) and I am not sure why nothing prints to the console. I am using the program DrJava in case anyone is wondering.

Here is my code for reference:

import java.util.Scanner;

  public class PrintDigits {
    public static void main(String [] args) {
       Scanner scnr= new Scanner(System.in);
       int userInput = 0;
       int positiveInt = 0;

    System.out.println("enter a positive integer:");
    userInput = scnr.nextInt();

    positiveInt = userInput % 10;
    System.out.println(positiveInt);


 return;
 }
}

Solution

  • All that that warning says is tha you never call scnr.close(); anywhere in your code. To get it to go away, just call scnr.close(); after you are done using the scanner.

    import java.util.Scanner;
    
    public class PrintDigits {
    public static void main(String [] args) {
       Scanner scnr= new Scanner(System.in);
       int userInput = 0;
       int positiveInt = 0;
    
        System.out.println("enter a positive integer:");
        userInput = scnr.nextInt();
    
        positiveInt = userInput % 10;
        System.out.println(positiveInt);
    
        scnr.close();
        return;
        }
    }