Limited number of tries to a simple game? - java

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);
}

Related

Java beginner -Trying to let player quit the game

I'm a beginner making a guessing game and I am trying to let the player quit the game by making their guess -1. Currently, if I enter -1 it says Too low and asks me to keep guessing and the player cannot quit the game until they guess the number.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char choice;
do {
int randomNum = (int) (Math.random() * 100 + 1);
int guess = 0;
while (guess != randomNum) {
System.out.println("Guess a number between 1-100");
guess = scan.nextInt();
if (guess > randoomNum) {
System.out.println("Too high.");
}
else if (guess < randoomNum) {
System.out.println("Too low.");
}
else if (guess > 0) {
System.exit(0);
System.out.println("GAME OVER");
System.out.println("the number was " + randomNum + ".");
}
else {
System.out.println("Correct! Well done!");
}
}
System.out.println("\nPlay again? (Y/N)");
choice = scan.next() .charAt(0);
} while (choice == 'Y' | choice =='y');
System.out.println("GAME OVER");
}
The existing code needs to be modified slightly: the condition with exit should be checked before comparing to the randomNum.
Other issues to be addressed:
Use input for Scanner instance
Perform System.exit after printing goodbye message
Scanner input = new Scanner(System.in);
char choice;
do {
int randomNum = (int) (Math.random() * 100 + 1);
int guess = 0;
while (guess != randomNum) {
System.out.println("Guess a number between 1-100, or -1 to exit");
guess = input.nextInt();
if (guess == -1) {
System.out.println("GAME OVER");
System.out.println("the number was " + randomNum + ".");
System.exit(0);
}
if (guess > randomNum) {
System.out.println("Too high.");
}
else if (guess < randomNum) {
System.out.println("Too low.");
}
else {
System.out.println("Correct! Well done!");
}
}
System.out.println("\nPlay again? (Y/N)");
choice = input.next().charAt(0);
} while (choice == 'Y' || choice =='y');
System.out.println("GAME OVER");

Random # Guessing Game Infinite Loop

For my Java class, I'm supposed to make a random number guessing game. I've been stuck on a loop I created for the past couple of days. The output of the program is always an infinite loop and I can't see why. Any help is very much appreciated.
/*
This program will generate a random number.
It will ask the user to guess what number was generated and say
if the guess is too high or low.
*/
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0)
{
if(userGuess > randNum){
System.out.println("Too high");
}
else if(userGuess < randNum){
System.out.println("Too high");
}
else{
System.out.println("Something is very wrong.");
}
}
if(userGuess == randNum){
success++;
System.out.println("You got it! Play again?");
}
}
}
You put the if that checks if the input is equal to the number outside the while, so the cycle never ends.
Here is the code fixed:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
int success = 0;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
while(success == 0) {
if(userGuess > randNum) {
System.out.println("Too high");
} else if(userGuess < randNum) {
System.out.println("Too high");
} else if(userGuess == randNum) {
success++;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}
I fixed it! I added breaks after each fail condition so that I wouldn't get an infinite loop. I tried this earlier, but I kept getting errors.
This is the completed code:
import java.util.Scanner;
import java.util.Random;
public class RandomNumGame {
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int randNum = rand.nextInt(20);
System.out.println("Number is : " + randNum);
int userGuess = 0;
boolean success = false;
System.out.println("Guess the number: ");
userGuess = input.nextInt();
input.close();
while(success == false){
if(userGuess > randNum) {
System.out.println("Too high,try again");
break;
} else if(userGuess < randNum) {
System.out.println("Too low");
break;
} else if(userGuess == randNum) {
success = true;
System.out.println("You got it! Play again?");
} else {
System.out.println("Something is very wrong.");
}
}
}
}

Java guess game. How do I input data validation(range checking) and how do I input guesses?

I have a project Im working on for class. Its a guessing game that gets a random number and the user guesses what it is. Ive got a working version of the project, but according to my instructions, it needs data validation(range checking would be best) and it also needs to display a certain message depending on how many tries it takes the user to guess correctly. If its less than 3, it should say something like "Good job!" If its more than 3 but less than 7, it should say something like "Need more practice." If its more than 7 it should say something like "Need way more practice." I dont want to have to de-construct my whole project, I would like to just add into it, and tweak accordingly. Can someone give me a way of coding these things?
Heres my code:
import java.util.Scanner;
public class GuessingGameCalc {
private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max);
System.out.println(" ");
}
public static int calculateRandomValue(int max){
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}
public static void main(String[] args){
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;
while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
System.out.println("Too low! Guess higher!");
}else if (userEntry > unit) {
System.out.println("Too high! Guess lower!");
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
break;
}
counter++;
}
System.out.println("Would you like to try again? Yes or No?");
prompt = sc.next();
System.out.println("Goodbye!");
}
}
public static void validateTheData() { }
}
Seems all you need to do is passing counter variable to validateTheData method and output your message, like this:
...
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();
if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}
if (userEntry < unit) {
if( (unit - userEntry) > 10 ){
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
validateTheData(counter);
break;
}
counter++;
}
...
public static void validateTheData(int count) {
if( count < 3){
System.out.println("Good job!");
} else if( count < 7 ){
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}

printing a print statement after a certain amount of tries in a loop

I am new to coding. I created a guessing game, and it works well but, I would like to know how to make it so that after the user attempts guessing the number 3 times, they get a hint which I put on the last line, but it is currently unreachable, and I do not know how to make the statement reachable, and in the do while loop. I am currently stuck. Thank you
import java.util.Scanner;
public class guessing_game {
public static void main (String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
int tries = 0;
do {
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num) {
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
}
else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}while(tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}
There are a few flow issues with your program, but here is a simple way to fix it up.
First of all, you are not actually using the value of guess when you return it from your run() method, so that can be removed.
Also, in cases like this, you would not want to use a do/while loop, but just while. You want to keep repeating the prompt until the user guesses correctly. So add a boolean to allow you to check if they won:
boolean correct = false; - We set it false to begin because they haven't won yet.
Now, instead of calling run() again after every guess (which resets the tries count every time, just let the while loop do its job and repeat itself. Hence, we need to move the prompt input into the while loop.
Here is a complete code listing of the changes:
import java.util.Scanner;
public class guessing_game {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
// Change the return type to void as you never use the value returned
public static void run(Scanner kb) {
int num = 44;
// Add a boolean to determine if the game is won
boolean correct = false;
int tries = 0;
while (!correct) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
} else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
} else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
} else if (guess == num) {
// Flag the guess as correct; this will exit the loop after this run
correct = true;
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
} else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}
}
}
1.You are recursively calling run() method and every time you call this method, a new variable try will be created and initialised to zero.
2. Your recursive call is before the condition check and due to the same reason the logic may never reach the condition check.
To make this work with minimal changes, you can use the following code. But this is not the best as it does not resolve the above shortcomings
import java.util.Scanner;
public class guessing_game {
static int tries = 0;
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc()
{
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb)
{
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
do{
tries++;
if(tries>=3) break;
if (guess < num)
{
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0))
{
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num)
{
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num)
{
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y"))
{
run(kb);
}
else if (choice.equalsIgnoreCase("n"))
{
System.exit(0);
}
}
}while( tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}

Java HiLo program stops

Right now im making a HiLo game in java and i have a few problems, not sure tho if im doing it right since im very new into java.
I having problem with getting the two ints "answer" and "guess" to the 3rd method.
and i must use 3 methods in this task.
Method 1: asking for what lvl the user wants.
Method 2: The program picks a random number between max and lets the user guess.
Method 3: Will see if the guess is == to answer and if not, it lets the user to try again. and at the same time i have to save all the tries from the user.
import java.util.Scanner;
import java.util.Random;
public class oneagain {
public static void main(String[] args) {
System.out.println("Welcome HiLo!");
System.out.println("What lvl?");
System.out.println("1. Easy (1-10)");
System.out.println("2. Medium (1-100)");
System.out.println("3. Hard (1-1000)");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
int tries = (playGame(choice));
}
public static int playGame(int choice) {
Scanner sc = new Scanner(System.in);
int tries = 0;
if (choice == 1) {
System.out.println("Guess a number between 1 and 10");
int answer = (int) (Math.random() * 11) + 1;
int guess = sc.nextInt();
}
if (choice == 2) {
System.out.println("Guess a number between 1 and 100");
int answer = (int) (Math.random() * 101) + 1;
int guess = sc.nextInt();
}
if (choice == 3) {
System.out.println("Guess a number between 1 and 1000");
int answer = (int) (Math.random() * 1001) + 1;
int guess = sc.nextInt();
}
return tries;
}
public static void giveResponse(int answer, int guess) {
if (choice == 1) {
int tries = 0;
Scanner sc = new Scanner(System.in);
boolean y = false;
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 10:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 10:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
if (choice == 2) {
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
if (choice == 3) {
while (y == false) {
guess = sc.nextInt();
tries++;
if (guess == answer) {
y = true;
} else if (guess < answer) {
System.out.println("Guess was too low!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess > answer) {
System.out.println("Guess was too high!");
System.out.println("Guess a number between 1 and 100:");
} else if (guess == answer) {
System.out.println("Score!");
System.out.println("You succeeded in " + tries + " attempt");
}
}
}
}
}
}
}
}
}

Categories

Resources