Resetting a game to start over in java - java

I created a dice game between the user and computer that loops 10 rounds - but if one of the game rounds is a tie - then it will ask if you want to play again and restart the game. I'm having a problem with the last part as the game iterates over at random times now. Any suggestions?
import java.util.Random;
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("User vs. Computer Dice Game");
boolean Correct = false;
boolean Replay = false;
while(Replay == true) {
}
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for(int i =1; i<11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6)+1;
System.out.println("User rolled: "+usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6)+1;
System.out.println("Computer rolled: "+computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if(usernum == computernum) {
System.out.println("It\'s a tie!");
System.out.println("Do you want to play again? (Y/N) ");
System.out.println();
if (a.equalsIgnoreCase("N")){
Replay = true;
}
else {
Correct = false;
}
}
}
}
System.out.println();
}
}
}

Some notes:
You never set Correct=true.
Once inside the "while (Correct==false)" loop, you never test Replay.
There is no point in creating rand2. Just reuse rand1.
You have "for (int i=1;i<11;i++)" for the main loop.
Inside of that loop, and it's a tie, you ask if you want to play again, but there is nothing there to end the loop, so the inner for loop will continue to play out until you hit 11.
You might add a break statement when it's a tie to abort the for loop.
In fact, you're probably better off just aborting the loop and then asking the question again at the top of the while loop:
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for (int i = 1; i < 11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6) + 1;
System.out.println("User rolled: " + usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6) + 1;
System.out.println("Computer rolled: " + computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}
if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if (usernum == computernum) {
System.out.println("It's a tie!");
// Exit early from the for loop:
break;
}
}
}
else
{
Correct = true;
}
}

Related

How to add another level in Guess game using java that generates every attempt a new random number

Hello everyone I'm still new in java but I was trying to do this guess game that has 2 levels first one in a normal guess game the second level is that the user has 5 attempts to guess the number but each time he/she fails it generates a new random number but I can't link the 2 levels together when I pass the first level it gets me to the second but with the conditions of the first and doesn't generate a random number each attempt I hope you guys have the knowledge to let me know what kind of mistakes I made
package guessing_game;
import java.util.Random;
public class Game {
Random random = new Random();
private boolean gameOver;
private int secretNumber;
private int numberOfGuess;
public Game(int range) {
gameOver = false;
secretNumber = random.nextInt(10);
numberOfGuess = 0;
}
public boolean isGameOver() {
return gameOver;
}
public boolean guess(int n) {
if (gameOver) {
System.out.println("The game is over. "
+ "You can not guess again.");
} else if (n == secretNumber) {
System.out.println("You guessed right!"
+"let's go to next level.");
gameOver = false;
} else {
if (n < secretNumber) {
System.out.println("Your guess is too low.");
} else {
System.out.println("Your guess is too high.");
}
numberOfGuess++;
if (numberOfGuess == 5) {
System.out.println("You have used up all of your guesses.");
gameOver = true;
}
}
return gameOver;
}
public void guess2(int n){
if (gameOver) {
System.out.println("The game is over. "
+ "You can not guess again.");
} else if (n == secretNumber) {
System.out.println("You guessed right!");
gameOver = true;
} else {
if (n < secretNumber) {
System.out.println("Your guess is not right.");
secretNumber=random.nextInt(10);
} else {
System.out.println("Your guess is not right.");
secretNumber=random.nextInt(10);
}
numberOfGuess++;
if (numberOfGuess == 5) {
System.out.println("You have used up all of your guesses.");
gameOver = true;
}
}
}
}
package guessing_game;
import java.util.Scanner;
public class Guessing_game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Game theGame = new Game(10);
while(theGame.isGameOver() == false){
System.out.println("Guess a number between 0 and 10:");
int n = input.nextInt();
theGame.guess(n);
if(theGame.guess(n)==false)
theGame.guess2(n);
}
}
}
Break the problem down into the steps you described.
You have two levels for guessing random a number.
First level: infinite guesses of a fixed random number
Second level: max 5 guesses of a random number that changes with each guess
Something like
public class Game {
public boolean play() {
Random random = new Random();
int level = 1;
int secretNumber = random.nextInt(10); // random number for all of level 1
// infinite guesses for level 1
do {
int guess = ... // get user input from keyboard
if (guess == secretNumber) {
level++;
}
} while (level == 1);
// level 2, only five guesses
for (int i = 0; i < 5; i++) {
// level 2, random number changes at each failed guess
secretNumber = random.nextInt(10);
int guess = ... // get user input from keyboard
if (guess == secretNumber) {
return true; // they won the game
}
}
return false; // they lost
}
}

How to let the user attempt many times?

import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}
public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}
All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.

How and where do i put a try/catch for only entering numbers in a number guessing game?

public class NewClass12 {
public static void main(String[] args) {
Random generator = new Random();
int numberToGuess = generator.nextInt(10 - 1) + 1;
int yourGuess;
Scanner input = new Scanner(System.in);
int guess = 0;
boolean win = false;
while (!win) {
System.out.println("Guess a number between 1 and 10: ");
yourGuess = input.nextInt();
guess++;
if (yourGuess < 1 || guess > 10) {
System.out.println("Guess is out of range! Enter a number between 1 and 10");
continue;
}
if (yourGuess == numberToGuess) {
win = true;
break;
}
if (yourGuess < numberToGuess) {
System.out.println("Your guess is too low");
} else {
System.out.println("Your guess is too high");
}
}
if (win) {
System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + guess + " tries.");
}
}
}
so, this is my code for a number guessing game. everything works fine so far execpt if i enter a letter as an input my code crashes. I guess i have to use a try/catch ? If yes where and how do i write it. I am a beginner so have mercy.
I this case, I would put the try catch wrapping where you read the user's input, like so:
public class NewClass12 {
public static void main(String[] args) {
Random generator = new Random();
int numberToGuess = generator.nextInt(10 - 1) + 1;
int yourGuess;
Scanner input = new Scanner(System.in);
int guess = 0;
boolean win = false;
while (!win) {
System.out.println("Guess a number between 1 and 10: ");
try{
yourGuess = input.nextInt();
guess++;
if (yourGuess < 1 || guess > 10) {
System.out.println("Guess is out of range! Enter a number between 1 and 10");
continue;
}
if (yourGuess == numberToGuess) {
win = true;
break;
}
if (yourGuess < numberToGuess) {
System.out.println("Your guess is too low");
} else {
System.out.println("Your guess is too high");
}
} catch (InputMismatchException err){
System.out.println("The input must be a number!");
input.next();
}
}
if (win) {
System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + guess + " tries.");
}
}
}
Note that we need the input.next() within the catch, in order to consume the invalid input, so it won't be in a loop.

Guessing Game, with a While loop

i'm currently trying to create a while loop for my program, a Guessing game. I've set it up so the user can create a max value i.e 1-500 and then the user can proceed to guess the number. When the number has been guessed, the User can press 1, to close, anything else to continue running the loop again.
My problem, is that the code gives me an error when trying to continue the loop, no compiling errros
This is my Code:
import java.util.Random;
import java.util.Scanner;
public class Gættespil2
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Indsæt loftets højeste værdi : ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
while (win == false)
{
System.out.println(" Gæt et tal mellem 1 og "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Koldere, gæt igen");
}
else if (guess > TAL) {
System.out.println("Varmere, Gæt igen!!");
}
}
System.out.println(" Tillykke du vandt...endeligt!!! ");
System.out.println(" tallet var" + TAL);
System.out.println(" du brugte " + FORSØG + " forsøg");
System.out.println("Slut spillet? tast 1.");
System.out.println("tryk på hvadsomhelst for at spille videre");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Simple answer. You didn't initialize all the necessary values within your 'keepPlaying' loop before beginning a second round after the player successfully completed the first round. See annotations to your code, below:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Enter a maximum limit: ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
// *** LOOK HERE ***
// Reset the 'win' flag here, otherwise the player receives an
// automatic win on all subsequent rounds following the first
win = false;
while (win == false)
{
System.out.println("Guess the number between one and "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Colder, guess again!");
}
else if (guess > TAL) {
System.out.println("Warmer, guess again!");
}
}
System.out.println("You've found the number!");
System.out.println("The number was: " + TAL + ".");
System.out.println("You guessed " + FORSØG + " times.");
System.out.println("To quit, enter 1.");
System.out.println("Provide any other input to play again.");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Sorry for the translation into English -- I had to make sure I was reading things correctly. You might also want to substitute "higher" and "lower" for "warmer" and "colder." "Warmer" and "colder" tend to suggest a proximity to the correct answer, as opposed to the direction in which that correct answer lies.

int variable remains at 0, while loop not running properly as a result

What I really am stuck with is the second to last variable userGuessDifference. It remains at zero making my second while loop not run properly as it just keeps going back to the first else if statement.
public class GuessingGame {
/**
* #param args
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
int userGuessDifference = (Math.abs(correctAnswer) - Math.abs(userGuess));
boolean flag = false;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10)
{
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
}
else if (difficulty == 25)
{
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
}
else if (difficulty == 50)
{
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
}
else
{
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (!flag || (counter <= guesses))
{
if (userGuess == correctAnswer)
{
System.out.println("CONGRATS YOU WIN!");
flag = true;
}
else if ((userGuessDifference <= (difficulty * .10)))
{
System.out.println("HOT!");
userGuess = keyboard.nextInt();
counter++;
}
else if ((userGuessDifference < (difficulty * .25)) && (userGuessDifference > (difficulty * .10)))
{
System.out.println("Warm...");
userGuess = keyboard.nextInt();
counter++;
}
else
{
System.out.println("Ice cold.");
userGuess = keyboard.nextInt();
counter++;
}
}
}
}
As #SotiriosDelimanolis wrote, you never reassign userGuessDifference. This should be done inside the while loop.
Moreover, there is another problem with your code: if you guess the number, the program just prints "CONGRATS YOU WIN!" forever, but it seems to me that you wanted to quit from the while loop once the user guesses the number (I guess the flag variable was introduced for this reason).
I slightly changed your code in order to meet this requirement:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10) {
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
} else if (difficulty == 25) {
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
} else if (difficulty == 50) {
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
} else {
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (counter <= guesses) {
// int userGuessDifference = (Math.abs(correctAnswer) - Math
// .abs(userGuess));
int userGuessDifference = Math.abs(correctAnswer - userGuess);
if (userGuess == correctAnswer) {
System.out.println("CONGRATS YOU WIN!");
break;
}
else if ((userGuessDifference <= (difficulty * .10))) {
System.out.println("HOT!");
}
else if ((userGuessDifference < (difficulty * .25))
&& (userGuessDifference > (difficulty * .10))) {
System.out.println("Warm...");
}
else {
System.out.println("Ice cold.");
}
userGuess = keyboard.nextInt();
counter++;
}
}
}

Categories