Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resource leak: 'sc' is never closed

Program to count how many times a particular character, letter or number occur in a sentence.

However I keep getting message:

Resource leak: 'sc' is never closed

I am using Java and Eclipse. What should I do?

import java.util.Scanner;
class Number-count {
    public static void number - count(String args[]) {
        String s;
        char ch;
        int count = 0;
        Scanner SC = new Scanner(System. in );
        System.out.println("Enter a sentence");
        String str = sc.nextLine();
        System.out.println("Enter a character to be searched for occurence");
        s = sc.nextLine();
        char c = s.charAt(0);
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            if (ch == c) {
                count++;
            }
        }
        System.out.println("Character " + c + " occur " + count + " times");
    }
}
like image 550
user7792568 Avatar asked Sep 06 '25 03:09

user7792568


2 Answers

Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method

SC.close();
like image 138
Omar El Halabi Avatar answered Sep 07 '25 21:09

Omar El Halabi


after your scanner work completed put: sc.close();

It is working 100%

like image 23
user10098954 Avatar answered Sep 07 '25 20:09

user10098954



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!