I am having an issue with my Nim Game running infinitely on the third option of my method. The code runs the game and presents the winner but it runs infinitely. The third method is used in this code to run the game many different times and record how many times each computer has won.
import java.util.Scanner;
public class NimGame
{
public static void main(String[] args)
{
int computerMove = 0;
int computer2Move = 0;
int userMove = 0;
int elementsRemaining = 0;
int take = 0;
int mode;
int times;
int initial = 0;
int comp1wins = 0;
int comp2wins = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Which mode would you like to run the game?");
System.out.println("1) Player Mode ");
System.out.println("2) AI vs AI Single Mode");
System.out.println("3) AI vs AI building mode");
mode = sc.nextInt();
if(mode==1)
{
System.out.println();
System.out.println();
System.out.println("Enter number of elements to start.");
elementsRemaining = sc.nextInt();
System.out.println("How many elements can you take at a time?");
take = sc.nextInt();
while(elementsRemaining > 0)
{
computerMove = getComputerMove(elementsRemaining, take);
System.out.println("Computer takes "+computerMove);
elementsRemaining -= computerMove;
System.out.println("Now there are "+elementsRemaining+" elements remaning.");
System.out.println();
if(elementsRemaining <= 0)
{
System.out.println("Computer wins!");
return;
}
System.out.println("How many elements do you want to remove? (1 to " + take + ")");
userMove = sc.nextInt();
while((userMove <1) || (userMove > take))
{
System.out.println("Taking " + userMove + " elements is not allowed, please choose from 1 to " + take + ".");
System.out.println();
userMove = sc.nextInt();
}
elementsRemaining -= userMove;
System.out.println("Now there are " + elementsRemaining + " elements remaining.");
System.out.println();
if(elementsRemaining <= 0)
{
System.out.println("You win!");
System.out.println();
return;
}
}
}
else if(mode==2)
{
System.out.println();
System.out.println();
System.out.println("Enter number of elements to start.");
elementsRemaining = sc.nextInt();
System.out.println("How many elements can you take at a time?");
take = sc.nextInt();
while(elementsRemaining > 0)
{
computerMove = getComputerMove(elementsRemaining, take);
System.out.println("Computer takes "+computerMove);
elementsRemaining -= computerMove;
System.out.println("Now there are "+elementsRemaining+" elements remaning.");
System.out.println();
if(elementsRemaining <= 0)
{
System.out.println("Computer 1 wins!");
return;
}
computer2Move = getComputer2Move(elementsRemaining, take);
System.out.println("Computer takes "+computerMove);
elementsRemaining -= computerMove;
System.out.println("Now there are "+elementsRemaining+" elements remaning.");
System.out.println();
if(elementsRemaining <= 0)
{
System.out.println("Computer 2 wins!");
return;
}
}
}
else if(mode==3)
{
System.out.println("How many times would you like to run the game?");
times = sc.nextInt();
System.out.println();
System.out.println();
System.out.println("Enter number of elements to start.");
initial = sc.nextInt();
System.out.println("How many elements can you take at a time?");
take = sc.nextInt();
elementsRemaining = initial;
for(int i=0; i<times; i++)
{
while(elementsRemaining > 0)
{
computerMove = getComputerMove(elementsRemaining, take);
System.out.println("Computer takes "+computerMove);
elementsRemaining -= computerMove;
System.out.println("Now there are "+elementsRemaining+" elements remaning.");
System.out.println();
if(elementsRemaining <= 0)
{
System.out.println("Computer 1 wins!");
comp1wins++;
elementsRemaining = initial;
}
computer2Move = getComputer2Move(elementsRemaining, take);
System.out.println("Computer takes "+computer2Move);
elementsRemaining -= computer2Move;
System.out.println("Now there are "+elementsRemaining+" elements remaning.");
System.out.println();
if(elementsRemaining <= 0)
{
System.out.println("Computer 2 wins!");
comp2wins++;
elementsRemaining = initial;
}
}
}
System.out.println("Computer 1 wins: " + comp1wins);
System.out.println("Computer 2 wins: " + comp2wins);
return;
}
else
{
}
}
public static int getComputerMove(int left, int take)
{
if(left == 1)
{
return left;
}
else
{
return (int)(Math.random()*take)+1;
}
}
public static int getComputer2Move(int left, int take)
{
if(left == 1)
{
return left;
}
else
{
return (int)(Math.random()*take)+1;
}
}
}
If I had to make a guess on the issue, I would have to say there is a problem with the nested while loop in my for loop. Any help or suggested changes to make would be greatly appreciated.
ou are right. In case of elementsRemaining is lower the zero you set it to the initial value. So it is every time grater then zero at the beginning of the while loop. You should take a boolean variable to decides, if your run the while loop again or not.
In the last one else you write twice
if(elementsRemaining <= 0)
{
....
elementsRemaining = initial;
}
but the elementsRemaining <=0 is exactly the condition that is needed to exit the internal loop!
Related
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.
I am currently creating a pig game, and have most functions working.
I need the code to work where if player 1 decides to stop rolling, and player two decides to stop rolling, the game will loop back until one player reaches 20 points. Currently, the code ends after 1 run through.
import java.util.Random;
import java.util.Scanner;
public class Project3_Part1_Submit {
static int playerScore = 0;
static int playerTotal = 0;
static int dice = 0;
static final int FINAL_SCORE = 20;
static int playerTwoScore = 0;
static int playerTwoTotal = 0;
static boolean gameOver = false;
static boolean turnOver = false;
static char repeat;
static String input;
static Scanner key = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
PlayerOneTurn();
PlayerTwoTurn();
GameContinue();
if (playerTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 1 wins!");
}
if (playerTwoTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 2 wins!");
}
}
public static void PlayerOneTurn() {
while (turnOver == false) {
do {
System.out.print("Player 1 turn total is " + playerTotal); // welcome line
System.out.print(". Enter (r)oll or (s)top: ");
System.out.println("");
input = key.next(); // input = next key entered
repeat = input.charAt(0);
if (repeat == 'r') // if input letter = r
{
dice = rand.nextInt(3) + 1; // set dice to number between 1-6
System.out.println("Player 1 rolled: " + dice); // display number, signifying the amount rolled
if (dice == 1) // if the number rolled happens to be 1...
{
playerScore = 0; // reset score to 0
System.out.print("Player 1 lost their turn! ");
System.out.print("Player 1 total is " + playerTotal);
System.out.println("");
return;
}
else
{
playerScore += dice; // add dice amount to player score
System.out.print("Player 1 turn total is " + playerScore);// print out total amount earned
System.out.print(" Enter (r)oll or (s)top: "); // repeat question
System.out.println("");
input = key.next();
repeat = input.charAt(0);
if (playerScore >= 20) {
playerTotal = playerScore;
gameOver = true;
return;
}
}
}
else if (repeat == 's') // if neither option is called
{
return;
}
else
{
System.out.println("Incorrect entry, please try again"); // prompt retry
System.out.println("");
input = key.next();
}
}while(turnOver == false || dice != 1);
playerTotal += playerScore;
playerScore = 0;
if (playerTotal >= FINAL_SCORE) {
// System.out.println("YOU WIN!");
gameOver = true;
while (playerTotal >= FINAL_SCORE)
;
break;
}
}
}
public static void PlayerTwoTurn() {
System.out.println("success");
while (turnOver == false) {
do {
System.out.print("Player 2 turn total is " + playerTwoTotal); // welcome line
System.out.print(". Enter (r)oll or (s)top: ");
System.out.println("");
input = key.next(); // input = next key entered
repeat = input.charAt(0);
if (repeat == 'r') // if input letter = r
{
dice = rand.nextInt(3) + 1; // set dice to number between 1-6
System.out.println("Player 2 rolled: " + dice); // display number, signifying the amount rolled
System.out.println("");
if (dice == 1) // if the number rolled happens to be 1...
{
playerTwoScore = 0; // reset score to 0
System.out.print("Player 2 lost their turn! ");
System.out.print("Player 2 total is " + playerTwoTotal);
System.out.println("");
return;
}
else
{
playerTwoScore += dice; // add dice amount to player score
System.out.print("Player 2 turn total is " + playerTwoScore);// print out total amount earned
System.out.print(" Enter (r)oll or (s)top: "); // repeat question.
System.out.println("");
input = key.next();
repeat = input.charAt(0);
if (playerTwoScore >= 20) {
playerTwoTotal = playerTwoScore;
gameOver = true;
return;
}
}
}
else if (repeat == 's') // if neither option is called
{
turnOver = true;
return;
}
else
{
System.out.println("Incorrect entry, please try again"); // prompt retry
System.out.println("");
input = key.next();
}
}while(turnOver == false || dice != 1);
playerTwoTotal += playerTwoScore;
playerTwoScore = 0;
if (playerTwoTotal >= FINAL_SCORE) {
// System.out.println("YOU WIN!");
gameOver = true;
while (playerTwoTotal >= FINAL_SCORE)
;
break;
}
}
}
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
PlayerOneTurn(); //go back to playerOne
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
}
My GameContinue() function is what i created to go loop back to PlayerOne.
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
gameOver = false;
PlayerOneTurn(); //go back to playerOne
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
I know calling PlayerOneTurn(); will not loop it back to the start of the main method. I've tried calling all three methods again like this.
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
gameOver = false;
PlayerOneTurn(); //go back to playerOne
PlayerTwoTurn();
GameContinue();
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
Obviously that just caused a butload of errors. How should i go about having my code continue to loop back until the if statement in GameContinue() is met?
As Ecto has commented, you could use a while loop in the main function. It is shown here:
public static void main(String[] args) {
while (GameContinue()) {
PlayerOneTurn();
PlayerTwoTurn();
}
if (playerTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 1 wins!");
}
if (playerTwoTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 2 wins!");
}
}
Now obviously this would be an error as GameContinue() is a void method. To combat this you can change GameContinue() to this:
public static boolean GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) {
gameOver = false;
return true;
} else {
return false;
}
}
This would solve your problems and your code is minimally changed.
Ok, so I have created the following program. It is not yet complete but when the code comes to the end (y or n part) and the user decides to try again they don't get the option to enter a new bet it just uses the one entered from the first time.
(Please comment if you need help about understanding the code or thinking it might be hard for other people to understand)
import java.util.*;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; //variable to cancel whole loop
char yesNo; //if user wants to continue playing or not
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
do { //loop to test if the bet is legit
if(money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while(bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n)");
yesNo = kin.next().charAt(0);
int loopBreak = 0; //to break do while loop bellow
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while(loopBreak == 0);
if(play == 0) {
break;
}
}
}
}
}
Its all about nested while loop don't stop when it needed. Its like this
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
...
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while(loopBreak == 0);
if(play == 0) {
break;
}
}
}
After you get answer 'y' you don't break the nested while and program never get the
while(money > 0 && play == 1) {
--> System.out.print("Please Enter The Amount You Want To Bet: ");
--> double bet = kin.nextDouble();
//because below while loop continues to loop
while((bet <= money || bet > 0)) {
...
}
}
part. Anyways corrected code is here(i tried every possibility and it worked)
import java.util.*;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; //variable to cancel whole loop
char yesNo; //if user wants to continue playing or not
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
do { //loop to test if the bet is legit
if(money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while(bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n): ");
yesNo = kin.next().charAt(0);
int loopBreak = 0; //to break do while loop bellow
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak++;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play--; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n': ");
}
} while(loopBreak == 0);
if(play == 0 || loopBreak == 1) {
break;
}
}
}
}
}
Have a good day!
Another solution is to use labeled breaks/continues https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
However it should be used sparingly (or not at all). You probably can simplify it in some other way.
package test.test;
import java.util.Scanner;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; // variable to cancel whole loop
char yesNo; // if user wants to continue playing or not
//Labeled <-----------------
start: while (money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while ((bet <= money || bet > 0)) {
do { // loop to test if the bet is legit
if (money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while (bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n)");
yesNo = kin.next().charAt(0);
int loopBreak = 0; // to break do while loop bellow
do {
if (yesNo == 'y') { // take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
//Labeled continue <-----------------
continue start;
} else if (yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; // to cancel whole program
break;
} else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while (loopBreak == 0);
if (play == 0) {
break;
}
}
}
}
}
I'm fairly new to java and I was wondering how could I reset this game to ask another number after the user guessed it correctly?
Here's my code so far:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
if(guess == -1){
System.out.print("Thank you for playing the game!");
break;
}
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
Just wrap your entire code (except for the scanner initialization) in a while loop that is always true. That way, when one game ends, it will start a new one. Then, instead of breaking your game's while loop when the user enters a -1, just use System.exit(0), which will end your program with a status code of 0, indicating that the program executed successfully.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
while (true) {
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100) {
if (guess == -1) {
System.out.print("Thank you for playing the game!");
System.exit(0);
}
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
} else if (guess < a) {
System.out.print("The number is higher. Try again: ");
} else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
}
Wrap your code in a while (true) this will keep on running your code for ever and ever. Make sure you are also updating your random a after every game and your count. Then from there just check if guess is ever -1 and return when it is. When you call return it will end the method which ends your game.
Scanner keyboard = new Scanner(System.in);
while (true){
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess==-1){
System.out.print("Thank you for playing the game!");
return;
}else if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in "
+ count + " tries!");
}
}
}
You need to:
move your end game condition in the while condition like this while(guess != -1)
move the welcome greetings inside the loop
move the thank you greeting after the game loop is done
reset count and a when the user won a game in order to start fresh
reset guess on every iteration
Now even if the player guesses the number, the loop does not end and the game loop can be stopped only intentionally (by entering -1 = current break condition):
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() * 99);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game");
while (guess != -1) {
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
a = 1 + (int) (Math.random() * 99);
System.out.println("Congratulations. You guessed the number in " + count + " tries!");
count = 0;
}
guess = 0;
}
System.out.print("Thank you for playing the game!");
}
The code can be refactored even more, for example extract functionality into functions in order to make the code more readable. This also leads to easier maintanence should the variables change or should more conditions come. For example the code can be refactored like this:
import java.util.Scanner;
public class Question2 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int a = 0;
int count = 0;
int guess = 0;
startNewGame();
System.out.println("Welcome to the Number Guessing Game");
while (guess != -1) {
System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");
guess = keyboard.nextInt();
count++;
if (guess < 0 || guess > 100){
System.out.print("Out of bounds. Try Again: ");
continue;
}
if (guess > a) {
System.out.print("The number is lower. Try again: ");
}
else if (guess < a) {
System.out.print("The number is higher. Try again: ");
}
else if (guess == a) {
System.out.println("Congratulations. You guessed the number in " + count + " tries!");
startNewGame();
}
resetGuess();
}
System.out.print("Thank you for playing the game!");
}
private static int generateNewA() {
return 1 + (int) (Math.random() * 99);
}
private static void startNewGame() {
a = generateNewA();
count = 0;
}
private static void resetGuess() {
guess = 0;
}
}
Another solution is to use two nested loops, but IMO for this case loop in a loop is too much and makes the source unnecessary complex.
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++;
}
}
}