简体   繁体   English

我应该在哪里放置Scanner.close();?

[英]Where should I put a Scanner.close();?

i need to know where i should put a Scanner close in this code to stop resource leak. 我需要知道在该代码中应关闭扫描仪的位置,以防止资源泄漏。

public class guess_main {

    public static void main(String[] args) {

         Random numGenerated = new Random();
         int numToGuess = numGenerated.nextInt(100);
         int numTries =0;
         int Guess;
         boolean win = false;

         Scanner inputNum = new Scanner(System.in);

         while (win == false){

             System.out.println("Please guess a number between 1 and 100");
             Guess = inputNum.nextInt();
             numTries++;

             if (Guess == numToGuess){
                  win = true;
             }
             else if  (Guess < numToGuess) {
                 System.out.println("Your guess is LOW!");
             }

             else if (Guess > numToGuess){
                 System.out.println("Your guess is HIGH!");
             }
         }//End of loop

         System.out.println("You won in " + numTries + " goes. Well done!");
    }
}

Add it at the end of the loop. 在循环末尾添加它。

Things should be closed as soon as you are done using them. 使用完后,应立即关闭所有内容。 If you do anything else with the scanner afterwords, you will need to move it. 如果您对扫描仪后遗留字进行其他操作,则需要移动它。 For example, if you rewrite it to offer the option for another game, you will need to place the closing statement after your confirm that they don't want to play. 例如,如果您重写它以提供其他游戏的选项,则需要在确认他们不想玩之后放置结束语。

You should put it after the end of your loop: 您应该将其放在循环结束之后:

while (win == false) {
    ...Game logic...
}
inputNum.close();

What this does is close the input stream, so you don't have memory leaks. 这样做是关闭输入流,因此不会发生内存泄漏。

In addition to that, please follow Java coding conventions . 除此之外,请遵循Java编码约定 The only (non-indent related) breaches I saw was that Guess is capitalized, but it's an object, and guess_main should be GuessMain (Uppercase and using camelCase instead of underscores) but it's good to keep an eye out, just in case. 我看到的唯一(与缩进无关的)违规行为是Guess大写,但这是一个对象, guess_main应该是GuessMain (大写并使用camelCase而不是下划线),但是要GuessMain ,以防万一。

Addendum: As David Wallace pointed out, there is a method that might throw an exception. 附录:正如David Wallace指出的那样,有一种方法可能会引发异常。 If you don't care, then the above solution will work, but if you do, this is better: 如果您不在乎,则可以使用上述解决方案,但是如果这样做,则更好:

try (Scanner inputNum = new Scanner(System.in)) {
    ...Game logic...
} catch (InputMismatchException e) {
    e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM