BioMan
BioMan

Reputation: 53

Resorce leak conIn never closed

This code is giving me a resource leak:

conIn never closed

Why does this happen and how can I fix it?

package homeWork;
import java.util.*;

public class MainClass 
{

    public static void main(String[] args) 
    {
        Scanner conIn = new Scanner (System.in);
        ShoppingBag sb = new ShoppingBag(0.06f);

        int count = 0;
        float cost = 0.0f;

        System.out.print("Enter count (use 0 to stop): ");

        count = conIn.nextInt();
        while (count < 0);
       {
           System.out.print("Enter Cost");
           cost = conIn.nextFloat();
           sb.place(count, cost);

           System.out.print("Enter count (use 0 to stop): ");
           count = conIn.nextInt();
           System.out.print(sb);

       }
    }
}

Upvotes: 1

Views: 72

Answers (2)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41240

Closing a stream when it's no longer needed is very important — so important that your program uses a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.

Scanner conIn = new Scanner (System.in);

You need to close the resource stream (System.in). After the loop-end close the stream.

conIn.close();

Upvotes: 0

Idos
Idos

Reputation: 15320

You didn't call conIn.close(); on your Scanner object. (docs)

Upvotes: 1

Related Questions