Reputation: 5
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!");
}
}
Upvotes: 0
Views: 196
Reputation:
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. 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.
Addendum: As David Wallace pointed out, there is a method that might throw an exception. 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();
}
Upvotes: 0
Reputation: 830
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.
Upvotes: 1