java 警告:资源泄漏:“键盘”永远不会关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26208840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:29:38  来源:igfitidea点击:

Warning: Resource leak: 'keyboard' is never closed

java

提问by Ajay P

import java.util.Scanner;

public class LetterGrade {
  public static void main(String[] args) {
    char grade;
    String input;
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter grade awarded");

    input = keyboard.nextLine();

    grade = input.charAt(0);

    switch (grade) {
      case 'A':
        System.out.println("Grade was between 89.5 and 100");
        break;  
      case 'B':
        System.out.println("Grade was between 79.5 and 89.49"); 
        break;  
      case 'C':
        System.out.println("Grade was between 69.5 and 79.49");
        break; 
      case 'D':
        System.out.println("Grade was between 59.5 and 69.49");
        break;
      case 'F':
        System.out.println("Grade was below 59.5");
        break;
      default:
        System.out.println("Invalid grade inputted");
        break;
    }
  }
}

[line: 9] Warning: Resource leak: 'keyboard' is never closed

[line: 9] 警告:资源泄漏:“键盘”永远不会关闭

That's the warning that I'm receiving. I don't think the source is actually being leaked. But i don't know how to get it off so i can compile the code

这就是我收到的警告。我不认为源实际上被泄露了。但我不知道如何将其关闭以便我可以编译代码

回答by Elliott Frisch

It is safe to ignore that warning, and I would never close()a scanner that is wrapping the global System.in

忽略该警告是安全的,我永远不会close()使用包装全局的扫描仪System.in

回答by Abbath

You need to close the keyboard Scanner. keyboard.close().

您需要关闭键盘扫描仪。 keyboard.close().

回答by Kieran M

You opened the keyboard with:

你打开了键盘:

Scanner keyboard = new Scanner(System.in); 

This needs to be closed with the keyboard.close()method when the keyboard input is no longer needed.

keyboard.close()当不再需要键盘输入时,这需要使用方法关闭。