'在'永远不会关闭

时间:2014-09-20 22:51:16

标签: java java.util.scanner drjava

我的代码中有错误,它给了我一个警告

警告:资源泄漏:'in'永远不会关闭

我之前从未遇到过这个问题,实际上我尝试过我编写的旧程序,但它仍然给我同样的问题。我该如何解决这个问题?

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).");



   }
} 

1 个答案:

答案 0 :(得分:2)

您只需要在功能结束时关闭扫描仪:

in.close();

像这样:

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

还要看看here