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. 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();
}
Related
A little confused on where to put another if-else statement after one. like do I put it under the if statement ("have you registered to vote yet?" ) or do i put it under the else statement?
I wanted it to answer if yes then it would print out "you can vote" and if no then it would print out "You must register before you can vote"
here's the code
import java.util.Scanner;
public class voting {
public static void main(String[] args) {
int yourage, votersage;
votersage = 18;
Scanner input = new Scanner(System.in);
System.out.println("How old are you? ");
yourage = input.nextInt();
if (yourage >= votersage) {
System.out.println("Have you registered to vote?");
}
else {
System.out.println("You are too young to vote");
}
}
}
I think this works to how you want it. You may need to change around the input'Registered as I am a bit rusty with inputs but I think this should work?
if (yourage >= votersage) {
Scanner input = new Scanner(System.in)
System.out.println("Have you registered to vote?");
Registered = input.next();
if Registered = ("Yes") {
System.out.println("You can vote");
}
else if Registered = ("No"){
System.out.println("You need to register to vote");
}
else:
System.out.println("INVALID INPUT")
}
else {
System.out.println("You are too young to vote");
}
For elif statements you put the elif before the else, but make sure to add a clause for the elif statement to run just like you did with the original if statement.
if (yourage >= votersage) {
System.out.println("Have you registered to vote?");
}
else if (yourage <= votersage){
System.out.println("You must register before you can vote.");
}
else {
System.out.println("You are too young to vote");
}
Nested if statement work in these scenarios...
if (yourage >= votersage)
{
System.out.println("Have you registered to vote?");
bool registered = input.next();
if(registered)
{
System.out.println("You can vote");
}
else
{
System.out.println("Please get yourself register on voting portal!");
}
}
else {
System.out.println("You are too young to vote");
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm new at java and i tried to make a Guess The Number game.
When the loop starts, i want to check if the user has any tries left.
if (remain > 1);
then after each end of the loop I want to subtract 1 from the tries.
I also tried to gather 1 after each loop ends.
byte tries = 5, remain=(byte)(--tries);
When user is out of tries i want to break the loop and break the game:
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
Here's my code:
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte tries = 5, remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1);
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
Code works perfectly but it won't break when user is out of tries.
tries variable should be initialized outside the while loop and the if statement was being closed using a ';'
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
byte tries = 5; // tries should be initialized outside the loop
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1) { // You were using ; and this if statement was closed
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
I think you are misunderstanding a lot of concepts. Here's a commented version :
public class Master {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// The number to found
double numberToFound = (byte)(Math.random() * 21);
// The user number will be stored here
byte userInput = 0;
// The number of tries left
byte tryLeft = (byte) 5;
do {
// Ask the User an number
System.out.print("Choose a number between 1 and 21 :");
userInput = scanner.nextByte(); // Store it
// Test the number
if (userInput > numberToFound) {
System.out.println("You are lower than the number!");
} else {
System.out.println("You are higher than the number!");
}
tryLeft--; // We remove one try
} while(tryLeft > 0 && userInput != numberToFound); // We loop until there are no more try OR we found the number
// Last time check (we check why we exited the loop)
// The user found the number
if (numberToFound == userInput)
System.out.println("You have guessed the number!");
else // The user has no more tries left
System.out.println("You haven't guessed the number!");
}
}
You should avoid using while(true) if you have a breaking condition for better readability.
You can try this code.
I changed some datatypes and added the decreasing of the remain variable inside the loop.
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int number = (int)(Math.random() * 21);
int tries = 5;
int remain = tries;
while(true){
System.out.print("Choose a number between 1 and 21:");
int user = scanner.nextInt();
// User input
System.out.println(remain);
if (remain > 1) {
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
--remain;
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
First of all, you can check if the "remain" is bigger than 0 and not 1, and your code will do the job as you planned (and you don't need to check == 0 at the else) :)
Second of all small comments to make your code more arranged:
Work with parameters that are comfortable to you like int (easier to debug and work with) you should use byte only if the code really needs it.
Move parameters that you use only to check them outside the loop like tries (think on that you will define this variable on every loop iteration and you don't need to).
Add to the params you are not going to change (like tries & number after you moved outside the loop) final it will be more clear that you are not going to change this param anymore.
Other than that looks great, good luck! :)
My code is running fine, but every line where I use a scanner it warns me that there is a "Resource leak; 'userGuess' is never closed" I don't understand what it means and could use some help solving it. Also if there is anything else in my code worth fixing I could use the help. Be warned I have a limited knowledge of Java programming. I also cannot get my TryCounter++ to work...
package masterMind2_1;
import java.util.Scanner;
public class MasterMind2_1 {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is(The Numbers Range from 1-4)");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Declare Array
int [] answerArray;
answerArray= new int [4];
//Initialize Array
//Change these value to change the answers needed to win
answerArray[0]=2;
answerArray[1]=3;
answerArray[2]=2;
answerArray[3]=2;
// //Create Board
// System.out.println("-- -- -- --");
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
System.out.println("What is the first Number?");
Scanner userGuess = new Scanner(System.in);
int num = userGuess.nextInt();
if (num==answerArray[0]) {
guessedCount++;
}
System.out.println("What is the Second Number?");
Scanner userGuess1 = new Scanner(System.in);
int num1 = userGuess1.nextInt();
if (num1==answerArray[1]) {
guessedCount++;
}
System.out.println("What is the Third Number?");
Scanner userGuess2 = new Scanner(System.in);
int num2 = userGuess2.nextInt();
if (num2==answerArray[2]) {
guessedCount++;
}
System.out.println("What is the Fourth Number?");
Scanner userGuess3 = new Scanner(System.in);
int num3 = userGuess3.nextInt();
if (num3==answerArray[3]) {
guessedCount++;
}
System.out.println("Your guess was "+ num+" "+num1+" "+num2+" "+num3);
if (num==answerArray[0]) {
System.out.println("First number was correct");
} else {
System.out.println("First number was incorrect");
}
if (num1==answerArray[1]) {
System.out.println("Second number was correct");
} else {
System.out.println("Second number was incorrect");
}
if (num2==answerArray[2]) {
System.out.println("Third number was correct");
} else {
System.out.println("Third number was incorrect");
}
if (num3==answerArray[3]) {
System.out.println("Fourth number was correct");
} else {
System.out.println("Fourth number was incorrect");
}
if (guessedCount==4) {
System.out.println("YAY you won!!");
guessedAll=true;
tryCounter=10;
} else {
System.out.println("Try again, except this time don't fail!");
guessedAll=false;
tryCounter++;
guessedCount=0;
}
}//What if I collected all of the values first
} //then told them if they were right or Wrong?
//Black and White Pegs?
//Fix TryCounter...Why isn't it working
}
Thank you for the Help!
The error message is telling you that you never call the close() method on your Scanner object. A worse problem is that you create multiple Scanners when you only need one.
As for tryCounter not working...
while(tryCounter<9 || !guessedAll)
This will keep looping if either part of the condition is true. My guess is that !guessedAll is evaluating to true beyond 9 guesses, so your loop keeps running. You'll need to change the || to an && to get it stop looping after 9 tries. (Also, print out the values of your variables or use a debugger so you can verify that they are changing when you expect them to.)
I stopped programming for a while now. Probably around 4 years, and I was just looking to mess around with it, so I decided to make a high:low number guessing game. (guess a number 1-100, program says if your guess is too high or too low) and I completely forgot how I would go about:
a) Once the user guesses the correct number, asking if they want to play again
b) If they don't guess the correct number (too high or too low), the program lets them guess again.
I understand that you would need loops, but I just forgot about how I would go about them
package highlow;
import java.util.Random;
import java.util.Scanner;
public class guessing {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Random rand = new Random();
int tries;
int correctNum = rand.nextInt(100);
System.out.println("enter a number 1-100");
int guess1 = input.nextInt();
if(guess1 < correctNum){
System.out.println("number is too low!");
}
else if(guess1 > correctNum){
System.out.println("Number is too high!");
}
else if(guess1 == correctNum){
System.out.println("correct!");
}
else{
System.out.println("not a valid option");
}
}
}
You need to wrap everything in a while loop so that it keeps repeating until the user guesses correctly:
// Make the scanner, get the random number etc... Put all the setup and
// stuff you don't want to be repeated here
while (true) {
System.out.println("enter a number 0-99"); // Changed from 1-100 because rand.nextInt(100)
// returns a number between 0 and 99
// You can do correctNum += 1 to make it between 1 and 100
// But put this in before the while loop starts
int guess1 = input.nextInt();
if(guess1 < correctNum){
System.out.println("number is too low!");
}
else if(guess1 > correctNum){
System.out.println("Number is too high!");
}
else if(guess1 == correctNum){
System.out.println("correct!");
break; // <---- Add this, this will make the loop stop when the
//player gets the answer correct and therefore the program will end
}
else{
System.out.println("not a valid option");
}
}
While loops repeat whatever is inside them until the statement inside their () is false. In our case the loop will go forever because true is inside the () but with the break statement, the loop will end when the user guesses correctly.
package highlow;
import java.util.*;
public class guessing
{
public static void main (String [] args)
{
boolean wantstoplay = true;
while(wantstoplay)
{
play();
System.out.println("Would you like to play again?");
Scanner kb = new Scanner (System.In);
if ((kb.nextLine().equals("yes") || (kb.nextLine().equals("Yes"))
wantstoplay = true;
else
wantstoplay = false;
}
}
public void play()
{
boolean playing = true;
int correctNum = (int) ((Math.Random() *100) + 1);
//selects random double from [1,101) and then rounds down
int tries = 0;
while (playing)
{
Scanner input = new Scanner(System.in);
System.out.println("enter a number 1-100");
int guess = input.nextInt();
if(guess < correctNum){
System.out.println("number is too low!");
tries++;
}
else if(guess > correctNum){
System.out.println("Number is too high!");
tries++;
}
else if(guess == correctNum){
System.out.println("correct!");
if (tries > 1)
System.out.println("Congrats, you guessed the right number. It only took you " + tries + " attempts!");
else
System.out.println("You guessed it first try! good job");
}
else{
System.out.println("not a valid option");
}
}
}
}
Above is some sample code that might be helpful.
I suggest making a play method, and then calling it in your main method.
This makes your code more organized and readable, because now you'll get the functionalities you desired without having 1 messy method with 2 loops in it.
You'll notice I included while loops rather than for loops. This is because while loops are ideal when you don't know how many times you're going to need to iterate.
The while in the main method checks to see whether the user would like another game. Notice that it assumes that the user wants to play at least one game. I did this by setting wantstoplay as true before we entered the loop, but this also could've been done with a do-while loop. For more, see (http://www.java-examples.com/do-while-loop)
The while in the play method checks to see whether the user needs to make another guess because he hasn't gotten the answer yet. Just like we can't know how many times the user wants to play before hand, we can't know how many guesses the user will take either.
Hope this helps you get back into programming!
EDIT
Thanks for your help guys. Here's the answer that helped me: https://stackoverflow.com/a/14903642
Here's the complete working code: http://pastebin.com/1kbipuAZ
End Edit
I'm supposed to make a simple cmd game that asks a user to input a number between a certain range of numbers. Then Player 2 is supposed to take a stab at guessing what that number is. The program keeps telling "Higher" or "Lower" until the player guesses the number. I figure I'm supposed to use some if/else statements and maybe while loops, but I can't figure out in what way. I either get an infinite loop, or it stops before I want it too. Here is what I have:
import java.io.*;
class game
{
public static void main (String[]args) throws IOException
{
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
String inData;
System.out.println("Welcome to The Game. Player One, please enter an integer higher than 0, and less than 1000...\n");
inData = stdin.readLine();
int number = Integer.parseInt(inData);
if(number >= 1000 || number <= 0)
{
System.out.println("Sorry, that number is out of the acceptable range on numbers...\n");
}
else
{
System.out.println();
}
String f1;
System.out.println("Player Two, Please enter a guess as to what Player One's number is...\n");
f1 = stdin.readLine();
int guess = Integer.parseInt(f1);
while(guess < number)
{
if(guess != number)
{
System.out.println("Higher. Please Guess Again...\n");
}
else
{
System.out.println();
}
break;
}
while(guess > number)
{
if(guess != number)
{
System.out.println("Lower. Please Guess Again...\n");
}
else
{
System.out.println();
}
break;
}
if(number==guess)
{
System.out.println("Congratulations. Thank you for playing...\n");
}
else
{
System.out.println();
}
}
}
I've tried different combinations of loops and statements etc. and I just can't get very far.
Your code is almost correct....
You need to break out of loop when second player guess correct number.
So,
while(guess != number)
In the loop you need to do comparison and print.
Also you need to get input each time in loop.
Code as below:
f1 = stdin.readLine();
int guess = Integer.parseInt(f1);
while(guess != number)
{
if(guess < number)
{
System.out.println("Higher. Please Guess Again...\n");
}
else if(guess > number)
{
System.out.println("Lower. Please Guess Again...\n");
}
f1 = stdin.readLine();
guess = Integer.parseInt(f1);
}
*Edited**
Complete working program below:
import java.io.*;
class game
{
public static void main (String[]args) throws IOException
{
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
String inData;
System.out.println("Welcome to The Game. Player One, please enter an integer higher than 0, and less than 1000...\n");
inData = stdin.readLine();
int number = Integer.parseInt(inData);
if(number >= 1000 || number <= 0)
{
System.out.println("Sorry, that number is out of the acceptable range on numbers...\n");
}
else
{
System.out.println();
}
String f1;
System.out.println("Player Two, Please enter a guess as to what Player One's number is...\n");
f1 = stdin.readLine();
int guess = Integer.parseInt(f1);
while(guess != number)
{
if(guess < number)
{
System.out.println("Higher. Please Guess Again...\n");
}
else if(guess > number)
{
System.out.println("Lower. Please Guess Again...\n");
}
f1 = stdin.readLine();
guess = Integer.parseInt(f1);
}
}
}
Here is the output:
Welcome to The Game. Player One, please enter an integer higher than 0, and less than 1000...
10
Player Two, Please enter a guess as to what Player One's number is...
2
Higher. Please Guess Again...
5
Higher. Please Guess Again...
7
Higher. Please Guess Again...
12
Lower. Please Guess Again...
11
Lower. Please Guess Again...
9
Higher. Please Guess Again...
10