I'm having trouble with my code. For some reason, each time I run the code the " if (guess <1 || guess >10 )
System.out.println ("Your guess needs to be between 1 and 10");" statement is counted as a guessing attempt. The goal is to not have the attempt count if the player is guessing out of the 1-10 range. I've tried a break;, but I can't get it right? Does anyone know how to break the loop and return to the guessing, if a user is out of range(without it counting as an attempt)?
Thank you
import java.security.SecureRandom;
import java.util.Scanner;
public class GuessTheNumber {
private Scanner input = new Scanner(System.in);
private SecureRandom randomNumbers = new SecureRandom();
private int numberOfGuesses;
public void play() {
numberOfGuesses = 0;
int magicNumber = 1 + randomNumbers.nextInt(10);
int guess = askForGuess();
while(guess != magicNumber){
// Some kind of loop, maybe while
numberOfGuesses++;
// is theGuess equal to magicNumber or is it
guess = input.nextInt();
// too high or is it too low
if (guess == magicNumber)
System.out.println("Yes, the number is " + magicNumber);
else if (guess > magicNumber)
System.out.println("Your guess is too high");
else if (guess < magicNumber)
System.out.println("Your guess is too low");
System.out.println ("Number of times guessed: "
+ numberOfGuesses );
// Display "correct in numberOfGuesses"
}
}
}
private int askForGuess( ) {
int guess = 0;
// prompt for a guess
System.out.println("Enter a number:");
if (guess <1 || guess >10 )
System.out.println ("Your guess needs to be between 1 and 10");
return guess;
}
}
You need to take input in the method "askForGuess()" also the increment will be done there too some thing like following
public class GuessTheNumber
{
private Scanner input = new Scanner(System.in);
private SecureRandom randomNumbers = new SecureRandom();
private int numberOfGuesses;
public void play() {
numberOfGuesses = 0;
int magicNumber = 1 + randomNumbers.nextInt(10);
int guess = 0;
while(guess != magicNumber){
// Some kind of loop, maybe while
guess = askForGuess();
// is theGuess equal to magicNumber or is it
if (guess == magicNumber)
System.out.println("Yes, the number is " + magicNumber);
else if (guess > magicNumber)
System.out.println("Your guess is too high");
else if (guess < magicNumber)
System.out.println("Your guess is too low");
System.out.println ("Number of times guessed: " + numberOfGuesses );
}
}
private int askForGuess( )
{
int guess = 0;
// prompt for a guess
System.out.println("Enter a number:");
guess = input.nextInt();
if (guess <1 || guess >10 )
System.out.println ("Your guess needs to be between 1 and 10");
else
numberOfGuesses++;
return guess;
}
}
Related
I cannot figure out how to add a limit to the number of guesses in my number guessing game. I have tried adding a for statement after the while statement but that made the code just stop at the tenth guess and there was no winner ever. I deleted the while statement and just did the for statement which ensured that the user got the correct answer every ninth guess. My code is divided into two classes as requested by my professor. I am including both below. I would appreciate all the help I can get. Thank you!
GuessingGame.java: Main Class
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while(!win) {
System.out.println("You are limited to ten attempts."
+ "Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (guess > 1000 ) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount -1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount -1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " +answer);
System.out.println("It took you " + tries + " tries");
}
}
You can add an if-statement inside the while loop.
public void doGuess() {
while(!win) {
System.out.println("You are limited to ten attempts."
+ "Guess a number between 1 and 1000: ");
guess = input.nextInt();
if(tries > 9) {
...whatever you want to happen when user has reached 10 guesses...
}
How would I limit the tries of a simple game to just three? I would think you would use a boolean. But not sure.
import java.util.Scanner;
public class guess {
public static void main(String[] args) {
int randomN = (int) (Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
do {
System.out.print("Enter your guess: ");
guess = input.nextInt();
if (guess == randomN) {
System.out.println("You won!");
} else if (guess > randomN) {
System.out.println("Too high");
} else if (guess < randomN) {
System.out.println("Too low");
}
} while (guess != randomN);
}
}
int attempts = 0;
do{
attempts++;
....
}while(guess != randomN && attempts < 3);
Use a flag. Initialize it as 0. If guess is correct then reset it as 0. If not increase by 1. Before each guess, check if flag > 2. If no let continue, if yes break.
You can increment during the failure of a guess. I believe the variable should be located outside of the loop. Then what's left is to add a portion that notifies the user of a failure when guesses run out.
public static void main(String[]args) {
int rNumber = (int)(Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
int tries = 0;
int success = 0;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
do {
System.out.println("Enter your guess: ");
guess = input.nextInt();
if(guess == rNumber) {
System.out.println("You guessed right! You win!");
success++;
} else if (guess < rNumber) {
System.out.println("Too low");
tries++;
} else if (guess > rNumber) {
System.out.println("Too high.");
tries++;
}
} while(tries != 3 && success != 1 || success != 1);
}
I have a quick question about this HiLo game that I have been trying to fix from a while now. When I run the program it counts guesses outside of the 0-10 range, but I don't want it to do that. How do I fix that? Here is my code.
import java.util.Random; // Random number generator class
import java.util.Scanner; // reads user inputs
public class HiLo
{
public static void main(String[] args)
{
// declare variables
final int MAX = 10;
int answer, guess;
int numberOfTries = 0;
String again;
Scanner Keyboard = new Scanner(System.in);
do
{
System.out.print(" I'm thinking of a number between 0 and "
+ MAX + ". Guess what it is: ");
guess = Keyboard.nextInt();
// guess
Random generator = new Random(); // Random number generator. 0 to 10.
answer = generator.nextInt(MAX) + 1;
if (guess > 10) // if guess is bigger than 10 then error message
{
System.out.println("ERROR – Your guess is out of the range 0 to 10.");
}
if (guess < 0) // if guess is smaller than 0 then error message
{
System.out.println("ERROR – Your guess is out of the range 0 to 10.");
}
while (guess != answer) // If guess is not the answer
{
if (guess > answer) // If guess is more than the answer
{
System.out.println("You guessed too high! \nTry again:");
guess = Keyboard.nextInt();
}
if (guess < answer)// If guess is less than the answer
{
System.out.println("Too Low! \nTry again:");
guess = Keyboard.nextInt();
}
numberOfTries = numberOfTries + 1;
}// end of the loop
// display result
if (guess == answer)
{
numberOfTries += 1;
System.out.println("YOU WIN!");
System.out.println("It took you " + numberOfTries + " tries!");
System.out.println();
System.out.print("Do you want to play again(Y/N)?");
}
Keyboard.nextLine(); // skip over enter key
again = Keyboard.nextLine();
numberOfTries = 0;
} while (again.equalsIgnoreCase("Y"));
} // end of class
} // end of main
You report the error but you don't continue; (and use a logical ||) like this
if (guess < 0 || guess > 10) {
System.out.println ("ERROR – Your guess is out of the range 0 to 10.");
again = "Y"; // <-- make sure we'll re-evaluate.
continue; // <-- Add then skip the rest of the loop body
}
Im making a guessing game for my class and I need some help for adding a "play again" feature at the end of the game when you've guessed the right number:
public class GuessingGame
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numtoguesses = rand.nextInt(1000) + 1;
int counter = 0;
int guess = -1;
while (guess != numtoguesses)
{
System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
guess = input.nextInt();
counter = counter + 1;
if (guess == numtoguesses)
System.out.println ("YOU WIN MOFO!");
else if (guess < numtoguesses)
System.out.println ("You're to cold!");
else if (guess > numtoguesses)
System.out.println ("You're to hot!");
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
}
}
One simple approach would be to move the code you've written into a function
public void play() {
...
}
and from main do something like:
do {
play();
playAgain = promptUser;
} while(playAgain);
Just put another while loop over everything.
boolean playing = true;
while(playing) {
while(guess != numtoguesses) { // All code }
System.out.println("Do you wish to play again? Y/N");
String answer = input.nextLine();
playing = answer.equalsIgnoreCase("y");
count = 0;
guess = -1;
}
Everything together:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int numtoguesses = rand.nextInt(1000) + 1;
int counter = 0;
int guess = -1;
boolean playing = true;
while(playing) {
while (guess != numtoguesses) {
System.out.print ("|" + numtoguesses + "|" + "Guess the right number: ");
guess = input.nextInt();
counter = counter + 1;
if (guess == numtoguesses)
System.out.println ("YOU WIN MOFO!");
else if (guess < numtoguesses)
System.out.println ("You're to cold!");
else if (guess > numtoguesses)
System.out.println ("You're to hot!");
}
}
System.out.println ("It took you " + counter + " guess(es) to get it correct");
System.out.println("Do you wish to play again? Y/N");
String answer = input.nextLine();
playing = answer.equalsIgnoreCase("y");
count = 0;
guess = -1;
numtoguesses = rand.nextInt(1000) + 1;
}
You should extract this in a few methods, but I'll leave that up to you.
There are a lot of options I can think about. The quickest:
-- place all the code between lines int numtoguesses = rand.nextInt(1000) + 1; (inclusive) and end of main method inside an infinite loop
-- at the end of your current code block, add an interogation to the user, asking him whether he/she wants to play again (you can define a convention for the pressed keys); this part is placed also inside the infinite loop
-- if he/she doesn't want to, break the (outer) infinite loop
So far I have,
package randomnumberguessinggame;
import java.util.Scanner;
public class RandomNumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
int count = 0;
do {
System.out.print("Enter a guess: (1-1000) ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
if (guess == secretNumber)
System.out.println("Your guess is correct. Congratulations!");
else if (guess < secretNumber)
System.out.println("Your guess is smaller than the secret number.");
else if (guess > secretNumber)
System.out.println("Your guess is greater than the secret number.");
} while (guess != secretNumber);
}
}
This code works but I need to know how to count the number of user inputs.
Thanks in advance.
Just add count++ under guess = keyboard.nextInt();
Just add one incrementation into your do while loop count = count + 1; as the last command. It would work anywhere in the do loop, but it's logical to put it after the input was processed.
Then add a line System.out.println("Number of guesses:"+count); under your loop.