So I wrote a java code for a numbers guessing game. The entire thing is pretty much done. It works by choosing a random number then asking the user for console inputs and then saying whether that is higher or lower than the random number. Once you guess it, it then asks if you want to play again. When you finally say no to this (be it one game or several) it prints out your Overall results including total games, total guesses, avg guesses/game and your best game. I have everything worked out except I cant figure out how to make it print your overall best game.
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) {
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.println("Guesses/game = " + totalGuesses/totalGames);
System.out.println("Best game = ");
}
}
In order to get the best game you need a keep track of the best best after each game, such as a variable that checks it there is a new best game after each game.
Keep track of the best score, which is the lowest number of guesses.
int bestGame = Integer.MAX_VALUE; // at the top
bestGame = Math.min(bestGame, numberOfTries); // at the end of your inner while loop
The worst possible score is the highest number of guesses, which is limited by Integer.MAX_VALUE, so you start there.
By the best game u mean minimum number of tries needed to answer is the best game.
/* int mintries,bestgame,gamenumber=0;
bestgamenumber=0;mintreies=Integer.MAX_VALUE:*/
Add the above lines above your while(play)
gamenumber++;
/*if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
betgame=gamenumber;
}*/
Add the if condition just before closing while(play).
So it will be like
int mintries;
mintreies=Integer.MAX_VALUE:
int gamenumber=0;
int bestgamenumber=0//if you want to print the which game is the best game(!st,2nd,3rd..) ;
while(play)
{
// do all your stuff
gamenumber++;
if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
bestgamenumber=gamenumber;
}
}
}
System.out.println("Game number +bestgamenumber+"was the best game with"+ mintries+"tries);
I am considering that you want to print which game (1st,2nd,3rd)is best and minimum tries made to guess the best game.Correct me if i am wrong.
To fit into the code you have already written, You could
Create a new 'global' variable, for example int bestGame = Integer.MAX_VALUE;.
Whenever the user is done with a game do a check if the current numberOfGuesses is smaller than the current bestGame, and if it is, then overwrite bestGame with the current numberOfGuesses.
At the end, you simply need to output bestGame.
Related
I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?
int answer = (int)(Math.random() * 100 + 1);
int guess = 0;
int guessCount = 0;
boolean playGame = true;
String restart;
Scanner scan = new Scanner(System.in);
while(playGame == true)
{
while (playGame == true)
{
System.out.println("Enter a number between 1 and 100: ");
guess = scan.nextInt();
guessCount ++;
System.out.println(answer);
if (guess < 1 || guess > 100)
{
System.out.println("You have entered an invalid number.");
guessCount --;
} else if (guess == answer)
{
System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
break;
} else if (guess > answer)
{
System.out.println("You've guessed too high! Guess again: ");
} else if (guess < answer)
{
System.out.println("You've guessed too low! Guess again: ");
}
}
System.out.println("Would you like to play again? Y/N");
restart = scan.next();
if (restart.equalsIgnoreCase("Y"))
{
playGame = true;
} else if(restart.equalsIgnoreCase("N"))
{
System.out.println("Thank you for playing!");
break;
}
}
The value in the variable 'answer' remains same since variable is a reference to what you have stored / Initialized or Assigned. It does not manipulate in itself. You have to rewrite the code for e.g. answer = (int)(Math.random()*100+1) at the point before game will be restarted or after it.
You're initializing the answer before the loop, it never changes. You have to assign answer a new value when the user chooses to play a new round. This is not the code I'd write, but here it is:
if (restart.equalsIgnoreCase("Y"))
{
answer = (int)(Math.random() * 100 + 1);
}
I'm new to Java programming and taking a college course where I have an assignment to create a Hi/Lo guessing game. The game provides up to 5 attempts for the user to input a number between 1 and 100 (inclusive). The program must provide the logic back of whether the answer is too low, too high or correct. The program must provide the option to play again after either winning or the 5 failed attempts.
I've recreated this program about 10 times :(. I cannot get he logic to work to follow the instructions above. I cannot stop the tries at 5 attempts... and I cannot get the program to execute a new game.
Any help is greatly appreciated. I've spent countless hours writing and re-writing this code with MANY different results - but not the intended ones.
This is my first time posting so, I apologize if the format to post is not correct.
I've looked through more forums and examples than I care to admit and none of code I've reviewed and tried implementing have given me the results of limiting the user input to 5 tries each time and ability to play again multiple times.
Here is my code:
public class HiLoGuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Initialize scanner and random number gennerator
Scanner input = new Scanner(System.in);
Random generator = new Random();
//State the rules of the game
System.out.println("The Hi-Lo Guessing Game. Guess a number between 1-100");
System.out.println("You have 5 attempts!");
/* define the variable Guess (user iput)
define the variable Answer (random generator)
define the variable Counter (track number of tries and limit to 5)
define the variable PlayAgain (Y/N question)*/
int guess = 0;
int answer = generator.nextInt(100)+1;
int counter = 1;
String playAgain;
boolean gameOver = false;
//Ask the Hi-Lo question - pick number 1-100 (inclusive)
//Provide feedback answer too high, too low or you win!
//Limit number of tries in the game to 5
while (guess != answer) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
counter++;
if (guess < answer) {
System.out.println("Your guess " + guess + " is too low. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess > answer) {
System.out.println("Your guess " + guess + " is too high. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess == answer) {
System.out.println("Your guess " + guess + " is correct! You win!");
System.out.println();
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
}
if (counter ==6) {
System.out.println("Sorry, you've reached your max atttempts.");
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
// Play again logic
boolean isValid;
do {
System.out.print("Would you like to play again (Y/N)?");
playAgain = input.next().toUpperCase();
isValid = playAgain.equals("Y") || playAgain.equals("N");
playAgain = input.next();
counter = 1;
if ( !isValid ) {
System.out.println("Error, please enter Y or N");
System.out.println();
}
} while (!isValid);
}
}
You can add an extra condition to your while-loop:
while (guess != answer && counter < 5) {
// ...
}
Alternatively, you can break the loop when you get a right answer:
while (counter < 5) {
// ...
if (answer == guess){
// ...
break;
}
}
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();
}
}
}
So I'm working on a copy of a simple Dice game that was an example from the Maxwell Sanchez YouTube JAVA on Eclipse tutorials. What I started playing around with is simple ways to implement a text based menu of sorts.
What I'm trying to accomplish is a Y or N input method of either restarting the program, or killing it. I'm a total noob, coming here after a tiny bit of Arduino. I'm liking JAVA but there are many things I don't understand.
My problem right now is, everything appears to work so far, except that if you get to the end and type N to quit, It requires 2 inputs of N to actually execute the else if statement. Is that something that is a bug? Or am I just mis-programing what I'm trying to accomplish.
import java.util.*;
public class diceGame
{
static int money;
static Scanner in = new Scanner(System.in);
static Random random = new Random();
static String userName;
static String tryAgain;
public static void main(String[] args)
{
money = 1000;
System.out.println("Welcome to this simple dice game! " +
"Please enter your name.");
String userName = in.nextLine();
System.out.println("Hey " + userName + ".");
rollDice();
}
public static void rollDice()
{
System.out.println("You have " + money + " coins!");
System.out.println("Please select a number (1-6) to bet on!");
int betRoll = in.nextInt();
System.out.println("Please place your bet!");
int betMoney = in.nextInt();
while (betMoney > money)
{
System.out.println("You don't have enough coins... you only " +
"have " + money + "coins.");
System.out.println("Please place a realistic bet!");
betMoney = in.nextInt();
}
int dice;
dice = random.nextInt(6)+1;
if (betRoll == dice)
{
System.out.println("You Win!");
money+=betMoney*6;
System.out.println("You have " + money + " coins.");
}
else
{
System.out.println("Snap! You lost your coins!");
money-=betMoney;
System.out.println("You have " + money + " coins.");
}
if (money <= 0)
{
System.out.println("You've lost all yer coins!");
System.out.println("Play again?" + " Type y or n");
if (in.next().equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (in.next().equalsIgnoreCase("n"))
{
System.out.println("Maybe next time...");
System.exit(0);
}
else
{
System.out.println("Invalid character");
}
}
else
{
rollDice();
}
}
}
Store the input in a variable, and compare it... or you'll have to input twice.
String choice = in.next();
if (choice.equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (choice.equalsIgnoreCase("n")) // <-- not in.next()
Every time you call in.next() you read user input.
if (in.next().equalsIgnoreCase("y"))
else if (in.next().equalsIgnoreCase("n"))
In this code, you are calling in.next() twice, once for each condition, so it will read two inputs.
You need to separate the reading from the comparison.
String input = in.next();
if (input.equalsIgnoreCase("y"))
else if (input.equalsIgnoreCase("n"))
for the following code, I need to stop the code by typing the word "quit", but without using "break" or "system.exit" statements. anyone can help me out? I think boolean could solve this but i have no idea how to use it.
I placed the quit statement in the first two lines of the loop,
but im not sure if it belongs there. Im in my learning phase, so dont be too strict :))
import java.util.*;
public class Game {
public static void main (String[]args){
Game guessing = new Game();
guessing.start();
}
public void start() {
System.out.println("Welcome to guessing game!");
System.out.println("Please enter the number between 1 and 1000");
Scanner input = new Scanner(System.in);
String playerName;
String currentGuess;
String quit = "quit";
boolean playGame = true;
int tries = 0; //number of times player guessed
int guess = 0; //number that player inputs
long startTime = System.currentTimeMillis(); //start timer after first guess
int randomNumber = (int) (Math.random() * 999 + 1); // generating random number
System.out.println(randomNumber); // to be deleted after game is finished
currentGuess = input.nextLine();
do{
if (currentGuess.equalsIgnoreCase(quit)) {
System.out.println("Thanx for playing");}
if (currentGuess.matches("[0-9]+")) {
int PlayerGuessInt = Integer.parseInt(currentGuess);
}
else {
System.out.println("You have netered non-numeric value,please try again");
currentGuess = input.nextLine();
continue;
}
guess = Integer.parseInt(currentGuess);
if(guess<1 || guess>1000 ){
System.out.println("The number is out of range! Please try again");
currentGuess = input.nextLine();
continue;
}
if (guess>randomNumber){
System.out.println("Oops,too high!");
currentGuess = input.nextLine();
tries++;
}
else if (guess<randomNumber){
System.out.println("Sorry, to low!");
currentGuess = input.nextLine();
tries++;
}
}
while (guess!=randomNumber);
if (guess==randomNumber){
tries++;
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Well done! You won the game in " + tries + " guesses " + "and " + gameTime/1000 + " seconds!");
System.out.println("Please enter your name: ");
playerName = input.nextLine();
}
}
}
Change your while loop so that it checks for the value of current guess being "quit". That way it will stop looping when the quit command is given e.g.
while(guess!=randomNumber && !currentGuess.equalsIgnoreCase(quit))
Put inside the while in one (or all of the if )
if (currentGuess.equals("quit") {
playGame = false
}
and change the while to be:
while (guess!=randomNumber && playGame)
Here's the answer:
Global boolean variable:
bool userWantsToQuit = false;
so if someone types int quit (shouln't it be "quit" because it's string?)
if (currentGuess.equalsIgnoreCase(quit))
{
userWantsToQuit = true; // we mark that someone wants to quit
System.out.println("Thanx for playing"); // we output message
continue; // skip execution of the rest (or you could use else if)
}
at the bottom you change while statement to stop the game if userWantToQuit is true:
(guess!=randomNumber && !userWantsToQuit)
It's been long time since I used java and I didn't test it, but it's definitely in good direction.