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
Related
I'm building a dice guessing game. the program has 5 die tosses. I've implemented hasNextInt() as it is the only one I can understand at the moment.
When I enter something that's not an Int it breaks out of the code but I want the program to continue for the rest of the goes (out of 5).
Also If the user guesses correctly I have to keep track of how many they get right.
If they guess wrong I have let them know what the die toss was, this keeps returning the first wrong die toss for the five goes.
At the end I have let the player know how many they got right out of 5.
This is my code so far
import java.util.Scanner;
public class Attempt11
{
public static void main(String args[]) {
int attempt = 1;
int userGuessNumber = 0;
int secretNumber = (int) (Math.random() * 6) + 1;
Scanner userInput = new Scanner(System.in);
System.out.println("Guess the next dice throw (1-6)");
do {
if (userInput.hasNextInt()) {
userGuessNumber = userInput.nextInt();
if (userGuessNumber == secretNumber) {
System.out.println("Congratulations you guessed right");
continue;
} else if (userGuessNumber < 1) {
System.out.println("Number must be between 1 and 6 inclusive, please try again ");
} else if (userGuessNumber > 6) {
System.out.println("Number must be between 1 and 6 inclusive, please try again ");
} else if (userGuessNumber > secretNumber) {
System.out.println("Hard luck the last throw was " + secretNumber);
} else if (userGuessNumber < secretNumber) {
System.out.println("Hard luck the last throw was " + secretNumber);
}
if (attempt == 5) {
System.out.println("You have exceeded the maximum attempt. Try Again");
break;
}
attempt++;
} else {
System.out.println("Enter a Valid Integer Number");
break;
}
} while (userGuessNumber != secretNumber);
userInput.close();
}
}
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! :)
Design an application that picks a random number 1 through 100, and then prompt the user to guess the number, warning the user they only have 5 tries remaining to guess correctly. After each guess, report to the user whether he or she is correct or guess was too high or too low. If guesses correctly, print out congratulatory message. If guess 5 times unsuccessfully, print a message saying the game is over. At the end of the game, prompt hte user to indicate whether or not he/she wishes to play again.
I specifically need help with the ending, and I guess also the layout of the code... I run it and it continually runs, I've tried using several websites and my textbook but no luck, thank you in advance!!
Java, Net beans 8.2
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main (String[]args)
{
int answer, guess,attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101)+1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
{
guess = scan.nextInt();
while (guess != 0)
{
if(guess==answer)
System.out.println("Right!");
else if (guess<answer)
System.out.println("Your guess was too LOW.");
else if (guess>answer)
System.out.println("Your guess was too HIGH.");
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
while (guess != answer && ++attemptsNum < maxAttempts)
if (attemptsNum == maxAttempts)
System.out.println ("The number was " + answer);
}
}
}
Enter your guess (0 to quit): 20
Your guess was too LOW
Enter your guess (0 to quit): 35
Your guess was too LOW
Enter your guess (0 to quit): 80
Your guess was too HIGH
Enter your guess (0 to quit): 74
Your guess was too HIGH
Enter your guess (0 to quit): 56
Right! Guesses:5
Play again (y/n)?
Couple of comments:
You need to work on your formatting of the code. This makes it a lot more readable.
Your generator generates a value between 1 and 101. It should just be answer = generator.nextInt(100)+1;
Your loops and some of your logic is wrong
I would suggest always creating a separate method outside public static void main. This is common practice, and this also allows you to call the method it self again.
This is how i would solve it:
import java.util.Random; import java.util.Scanner;
class Main {
public static Scanner scan = new Scanner(System.in);
public static void main (String[]args) {
runGame();
}
public static void runGame() {
String another = "";
int answer, guess,attemptsNum = 0;
final int maxAttempts = 5;
Random generator = new Random();
answer = generator.nextInt(100)+1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
while (guess != answer && attemptsNum < maxAttempts-1 && guess != 0 ) {
if(guess==answer)
System.out.println("Right!");
else if (guess<answer) {
System.out.println("Your guess was too LOW.");
attemptsNum++;
guess = scan.nextInt();
}
else {
System.out.println("Your guess was too HIGH.");
attemptsNum++;
guess = scan.nextInt();
}
}
System.out.println ("The number was " + answer);
System.out.println("Want to Play again?(y/n)");
another = scan.next();
System.out.println("another = " + another);
if(another.equals("y")) {
runGame();
} else {
System.out.println("Goodbye!");
}
}
}
But either way, just continue to practice. You will get the hang of it!
I see the outer while loop needs to be restructured and some of the logic is misplaced. Try the revised version, hope this helps. Comment me if you have any questions.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101) + 1;
while (another.equals("y") || another.equals("Y")) {
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
attemptsNum = 0;
while (guess != 0)
{
attemptsNum++;
if (guess == answer) {
System.out.println("Right!");
break;
} else if (guess < answer)
System.out.println("Your guess was too LOW.");
else if (guess > answer)
System.out.println("Your guess was too HIGH.");
if (attemptsNum == maxAttempts) {
System.out.println("The number was " + answer);
break;
}
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
}
System.out.println("Thanks for playing");
}
}
I can see that javapedia.net has answered first, but I have come up with this answer independently. I have added brackets for readability. attemptsNum++ is added to the if statements for a guess being too high or low.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(101) + 1;
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
while (guess != 0) {
if (guess == answer) {
System.out.println("Right!");
guess = 0;
} else if (guess < answer) {
System.out.println("Your guess was too LOW.");
attemptsNum++;
guess = scan.nextInt();
} else {
System.out.println("Your guess was too HIGH.");
attemptsNum++;
guess = scan.nextInt();
}
if (attemptsNum >= (maxAttempts-1)) {
System.out.println("The number was " + answer);
}
}
}
}
I am trying to develop a simple high low game that asks the user after playing if they would like to play again. If I remove the outer while loop the logic of the inner loop does exactly what I want it to do, however I am unsure how to wrap the inner loop with an outer loop that will ask the play again question and if the answer is yes put them back into the inner loop. Below is my code.
import java.util.Scanner;
import java.util.Random;
public class HiLoGuess {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100)+1; // Generates a random number for the game.
int count = 0; // Placeholder for the guess counter.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
String newgame = "y";
while (newgame.equalsIgnoreCase("y"))
{
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{
System.out.println ("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0 )
{
System.out.println("Your guess is too low, guess again");
}
else if (guess > answer)
{
System.out.println ("Your guess is to high, guess again");
}
else if (guess == answer)
{
System.out.println ();
System.out.println ("You guessed correctly, you win!!!");
System.out.println ("It took you " + count + " guesses");
}
}
System.out.print();
System.out.println("Play another game: y or n?");
newgame = scan.nextLine();
}
}
}
You need to put these initializations into the outer loop:
int guess = -1;
int answer = numb.nextInt(100)+1;
int count = 0;
Otherwise they keep the value from the last game and the inner loop will not be executed any more.
you never reset your guess, sentinel, or answer variables
so (guess != sentinel && guess != answer) always evaluates to false after the first time the game is played, and therefore the inner while loop never executes after the first game
while (guess != sentinel && guess != answer) //this is false after the first game because you don't reset variables
{ ...}
Update for OP comment:
to get your code to do what you want you need to add the resets between the outter and inner while loop like this
while (newgame.equalsIgnoreCase("y"))
{
guess = -1;
answer = numb.nextInt(100)+1;
count = 0;
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{ ...}
}
Replace newgame = scan.nextLine(); by this : newgame = scan.next();
And you need to initialise your variables inside your while loop, so that the flag is reseted to false and the random generate new result to guess.
public class Game
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
String newgame = "y";
while (newgame.equalsIgnoreCase("y")) {
int count = 0; // Placeholder for the guess counter.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100) + 1; // Generates a random number for the game.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
while (guess != sentinel && guess != answer) // Loop that ends when user enters a zero.
{
System.out.println("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0) {
System.out.println("Your guess is too low, guess again");
} else if (guess > answer) {
System.out.println("Your guess is to high, guess again");
}
else if (guess == answer) {
System.out.println();
System.out.println("You guessed correctly, you win!!!");
System.out.println("It took you " + count + " guesses");
}
}
System.out.println();
System.out.println("Play another game: y or n?");
newgame = scan.next();
}
}
}
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!