-4

HELP!

Inner while loop (askAgain) not working properly. I want it so that when the user presses 'y' to start an new game, it will exit inner loop and back out to outer whileloop (keepPlaying) and press 'n' to exit game.

If the user presses neither 'y' or 'n', any other keypressed, it will loop back to: askAgain, until the user made a valid choice.

The program is not working as expected. Please help.

import java.util.Random;
import java.util.Scanner;

public class Game {


    private  int       playerGuess;

    private  boolean   keepPlaying   = true;
    private  boolean   askAgain      = true;


    Random    randomNumber;   
    int       generatedYear; 
    int       generatedMonth; 
    int       generatedDay;   


    /**
     * 
     */
    public Date getRandomDate() {       

        randomNumber   = new Random();
        generatedYear  = randomNumber.nextInt(600) + 1600;
        generatedMonth = randomNumber.nextInt(12) + 1;
        generatedDay   = randomNumber.nextInt(31) + 1;  

        Date generatedDate = new Date (generatedYear, generatedMonth, generatedDay);

        return generatedDate;
    }   

    /**
     * 
     */
    public void guessTheDate() { 


        Scanner userInput   = new Scanner(System.in);

        while(keepPlaying) { 

            int ranDateYear= getRandomDate().getYear();

            System.out.println("New Game!!");
            System.out.println();
            System.out.print("Please guess the year. (0 - 2199): ");

            while(userInput.hasNext()) { 

                if(userInput.hasNextInt()) { 

                    playerGuess = userInput.nextInt();

                    if(playerGuess > ranDateYear) { 

                        System.out.println("Out of bounds, too high: " + playerGuess + " (Randomized Number: " +  ranDateYear+ ")");
                        System.out.println();
                        System.out.println("Try again!");
                        System.out.print("Please guess the year (0 - 2199): ");

                    }else if(playerGuess < ranDateYear) {

                        System.out.println("Out of bounds, too low:  " + playerGuess + " (Randomized Number: " + ranDateYear + ")");
                        System.out.println();
                        System.out.println("Try again!");
                        System.out.print("Please guess the year (0 - 2199): "); 

                    }else{      

                        if (playerGuess == ranDateYear) {

                            System.out.println("Correct! It is a match:  " + playerGuess + " (Randomized Number: " + ranDateYear + ")");
                            System.out.println();
                            System.out.print("Play again? (Y/N): ");

                            while (askAgain) {

                                while (userInput.hasNext()) {

                                    if (userInput.hasNext()) {

                                        String input = userInput.next();

                                        if (input.equalsIgnoreCase("y")) {

                                            keepPlaying = true;

                                        } else if (input.equalsIgnoreCase("n")){

                                            keepPlaying = false;

                                        } else {

                                            askAgain = true;
                                        }

                                        break;                              
                                    }


                                }

                            }

                        }                           
                    }   

                } else {

                    System.out.println("Invalid input, not a number.");
                    System.out.print("Enter another number: ");
                    userInput.next();

                }
            }   
        }

        System.out.println("The end. Thank you for playing!");
    }
}
Greg Schmidt
  • 4,471
  • 2
  • 10
  • 31

3 Answers3

0

Within your inner (askAgain) loop, you never change the value of askAgain to false, causing it to constantly stay true, which causes an infinite loop. Instead try this in your inner loop:

if(input.equalsIgnoreCase("y")) {
    keepPlaying = true;
    askAgain = false;
} else if(input.equalsIgnoreCase("n") {
    keepPlaying = false;
    askAgain = false;
} else {
    askAgain = true;
Teejosity
  • 16
  • 3
0

Replace

while (askAgain) {

                                while (userInput.hasNext()) {

                                    if (userInput.hasNext()) {

                                        String input = userInput.next();

                                        if (input.equalsIgnoreCase("y")) {

                                            keepPlaying = true;

                                        } else if (input.equalsIgnoreCase("n")){

                                            keepPlaying = false;

                                        } else {

                                            askAgain = true;
                                        }

                                        break;                              
                                    }


                                }

                            }

WITH

   while (true) {
       String input = userInput.next();
        if (input.equalsIgnoreCase("y")) {
            keepPlaying = true;break;
         } 
        else if (input.equalsIgnoreCase("n")){
             keepPlaying = false;break;
        } 
}

It Will solve the current problem of yes and no but it will not solve the main problem and you will create new question on SO asking for solution again. Actually the way you implemented your code is not very good.

Now use this code for a working of your project but mind you this is also not the best way to implement the code

import java.sql.Date;
import java.util.Random;
import java.util.Scanner;

public class JavaAZ {
    public static void main(String[] args) {
        Game myGame = new Game();
        boolean loop = false;
        do {
            loop = myGame.guessTheDate();
            if(!loop) System.out.println("The end. Thank you for playing!");
        }while(loop);

    }
}


 class Game{
     private  int       playerGuess;

        private  boolean   keepPlaying   = true;
        private  boolean   askAgain      = true;


        Random    randomNumber;   
        int       generatedYear; 
        int       generatedMonth; 
        int       generatedDay;   


        /**
         * 
         */
        public Date getRandomDate() {       

            randomNumber   = new Random();
            generatedYear  = randomNumber.nextInt(600) + 1600;
            generatedMonth = randomNumber.nextInt(12) + 1;
            generatedDay   = randomNumber.nextInt(31) + 1;  

            Date generatedDate = new Date (generatedYear, generatedMonth, generatedDay);

            return generatedDate;
        }   

        /**
         * 
         */
        public boolean guessTheDate() { 
            Scanner userInput   = new Scanner(System.in);
                int ranDateYear= getRandomDate().getYear();
                System.out.println("New Game!!");
                System.out.println();
                System.out.print("Please guess the year. (0 - 2199): "+ranDateYear);

                while(userInput.hasNext()) { 
                    if(userInput.hasNextInt()) { 
                        playerGuess = userInput.nextInt();
                        if(playerGuess > ranDateYear) { 
                            System.out.println("Out of bounds, too high: " + playerGuess + " (Randomized Number: " +  ranDateYear+ ")");
                            System.out.println();
                            System.out.println("Try again!");
                            System.out.print("Please guess the year (0 - 2199): ");

                        }else if(playerGuess < ranDateYear) {
                            System.out.println("Out of bounds, too low:  " + playerGuess + " (Randomized Number: " + ranDateYear + ")");
                            System.out.println();
                            System.out.println("Try again!");
                            System.out.print("Please guess the year (0 - 2199): "); 

                        }else{      
                            if (playerGuess == ranDateYear) {
                                System.out.println("Correct! It is a match:  " + playerGuess + " (Randomized Number: " + ranDateYear + ")");
                                System.out.println();
                                    while (true) {
                                         System.out.print("Play again? (Y/N): ");
                                            String input = userInput.next();
                                            if (input.equalsIgnoreCase("y")) {
                                                return true;

                                            } else if (input.equalsIgnoreCase("n")){
                                                return false;
                                            }
                                    }
                            }                           
                        }   

                    } else {

                        System.out.println("Invalid input, not a number.");
                        System.out.print("Enter another number: ");
                        userInput.next();

                    }
                }   
                return false;
        }
 }

THIS IS THE WORKING OF YOUR CODE IN YOUR WAY

import java.sql.Date;
import java.util.Random;
import java.util.Scanner;

public class Game {


    private  int       playerGuess;

    private  boolean   keepPlaying   = true;
    private  boolean   askAgain      = true;


    Random    randomNumber;   
    int       generatedYear; 
    int       generatedMonth; 
    int       generatedDay;   

    public static void main(String[] args) {

        Game g = new Game();
        g.guessTheDate();
    }
    /**
     * 
     */
    public Date getRandomDate() {       

        randomNumber   = new Random();
        generatedYear  = randomNumber.nextInt(600) + 1600;
        generatedMonth = randomNumber.nextInt(12) + 1;
        generatedDay   = randomNumber.nextInt(31) + 1;  

        Date generatedDate = new Date (generatedYear, generatedMonth, generatedDay);

        return generatedDate;
    }   

    /**
     * 
     */
    public void guessTheDate() { 


        Scanner userInput   = new Scanner(System.in);

        while(keepPlaying) { 

            int ranDateYear= getRandomDate().getYear();

            System.out.println("New Game!!");
            System.out.println();
            System.out.print("Please guess the year. (0 - 2199): "+ranDateYear);

            while(userInput.hasNext()) { 

                if(userInput.hasNextInt()) { 

                    playerGuess = userInput.nextInt();

                    if(playerGuess > ranDateYear) { 

                        System.out.println("Out of bounds, too high: " + playerGuess + " (Randomized Number: " +  ranDateYear+ ")");
                        System.out.println();
                        System.out.println("Try again!");
                        System.out.print("Please guess the year (0 - 2199): ");

                    }else if(playerGuess < ranDateYear) {

                        System.out.println("Out of bounds, too low:  " + playerGuess + " (Randomized Number: " + ranDateYear + ")");
                        System.out.println();
                        System.out.println("Try again!");
                        System.out.print("Please guess the year (0 - 2199): "); 

                    }else{      

                        if (playerGuess == ranDateYear) {

                            System.out.println("Correct! It is a match:  " + playerGuess + " (Randomized Number: " + ranDateYear + ")");
                            System.out.println();
                            System.out.print("Play again? (Y/N): ");

                            while (true) {
                                        String input = userInput.next();
                                        if (input.equalsIgnoreCase("y")) {
                                           keepPlaying = true;break;
                                        } 
                                        else if (input.equalsIgnoreCase("n")){
                                            keepPlaying = false;break;
                                        } 
                            }
break;
                        }                           
                    }   

                } else {

                    System.out.println("Invalid input, not a number.");
                    System.out.print("Enter another number: ");
                    userInput.next();

                }
            }   
        }

        System.out.println("The end. Thank you for playing!");
    }
}
Sundeep
  • 444
  • 2
  • 11
  • I am trying to use the public void method and not the public Boolean method. I want to be able to loop back from using the variable "keepPlaying" and "askAgain" where it loops when these variables are executed. – NERDY_IllegalException Jun 19 '18 at 01:50
0
if (userInput.hasNext()) {

    String input = userInput.next();    
    if (input.equalsIgnoreCase("y")) {    
          keepPlaying = true;   
          askAgain = false;
    } else if (input.equalsIgnoreCase("n")){    
          keepPlaying = false;  
          askAgain = false;  
    } else {    
          askAgain = true;
    }    
    break;                              
}

And refer to this Difference between next and nextline

EDIT:

replace while(userInput.hasNext()) { with a variable that tells the user is inputing so in the askAgain loop this variable will turn to false.

Try this:

    while(enteringInput) {

        try{
                playerGuess = userInput.nextInt();

                if(playerGuess > ranDateYear) { 

                    System.out.println("Out of bounds, too high: " + playerGuess + " (Randomized Number: " +  ranDateYear+ ")");
                    System.out.println();
                    System.out.println("Try again!");
                    System.out.print("Please guess the year (0 - 2199): ");

                }else if(playerGuess < ranDateYear) {

                    System.out.println("Out of bounds, too low:  " + playerGuess + " (Randomized Number: " + ranDateYear + ")");
                    System.out.println();
                    System.out.println("Try again!");
                    System.out.print("Please guess the year (0 - 2199): "); 

                }else{      

                    if (playerGuess == ranDateYear) {

                        System.out.println("Correct! It is a match:  " + playerGuess + " (Randomized Number: " + ranDateYear +")");


 System.out.println();
                        System.out.print("Play again? (Y/N): ");

                        while (askAgain) {           

                            System.out.print(askAgain);
                            while (userInput.hasNext()) {

                    String input = userInput.nextLine();    
                    if (input.equalsIgnoreCase("y")) {    
                        keepPlaying = true;   
                        askAgain = false;
                    } else if (input.equalsIgnoreCase("n")){                
                    keepPlaying = false;  
                        askAgain = false;
                                            enteringInput = false;  
                    } else {    
                        askAgain = true;
                    }    
                        break;   
                            }
                        }
                    }                           
                }  
                }catch(Exception e){
                   System.out.println("Invalid input");
                   userInput.nextLine();
                }                    
        }            
GamingRuru
  • 120
  • 13