Search code examples
javajava.util.scannerdrjava

'in' is never closed


there is a error in my code it is giving me a warning

Warning: Resource leak: 'in' is never closed

I have never had this problem before, in fact I tried old programs that I have written and it is still giving me the same issue. How do I fix this ?

import java.util.Scanner ;


public class CountVowels
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter a word: ");
      String word = in.next();

      int vowelCount = 0;
      for (int i = 0; i < word.length(); i++)
      {
         char currentCharacter = word.charAt(i);
         if (currentCharacter == 'a' || currentCharacter == 'A'
            || currentCharacter == 'e' || currentCharacter == 'E'
            || currentCharacter == 'i' || currentCharacter == 'I'
            || currentCharacter == 'o' || currentCharacter == 'O'
            || currentCharacter == 'u' || currentCharacter == 'U')
         {
            vowelCount++;
         }
      }
      System.out.println(vowelCount + " vowel(s).");



   }
} 

Solution

  • You will just need to close your scanner at the end of your function with:

    in.close();
    

    Like this:

    public static void main(String[] args)
    {
       Scanner in = new Scanner(System.in);
       // Do some stuff using the scanner
       in.close();
    }
    

    And also take a look here.