#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Location
    Boynton Beach, FL
    Posts
    2
    Rep Power
    0

    While loop not carrying out the way I'd like


    This is a basic guessing game, where the computer compares each players guess to a random #, and then announces the winner. The game ends with the option of playing again or exiting, which I am attempting to control with an exitCode variable and a while() loop.

    The program runs through seemingly fine up until the user decides to play again. After entering a 1 to play again, the program jumps back to collecting user names, but it skips over Player1, leaving it blank, and goes directly to Player2. I've played with it, left the computer for a day, come back and played some more, but still can't seem to solve this problem.

    I've included my whoIsCloser.java code as well as a sample output that will make clear the re-occurring problem.

    Any help is much appreciated, and please be nice, it's been several years since I've attempted anything with Java, just trying to refresh my memory a little before returning back to school in the Spring.

    Thank you,

    Justin

    Code:
    /*Justin Johnson
    **johnsonj561@gmail.com
    **October 5, 2012
    ** 
    **whoIsCloser is an attempt to refresh my memory. I took several programming courses back in 2008 and 2009,
    **I'm going back to school in the spring of 2013. Just got bored and started typing!
    **
    **Each user enters their name, the computer decides who is to go first through alphabetical comparison, and
    **each user guesses a number between 1-10. These guesses are then compared to the random # generated by computer,
    **and a winner is announced.
    **The game ends with the option of playing again or terminating.
    */
    
    
       import java.util.Scanner;
       import java.util.Random;
    
       public class whoIsCloser {
       
          public static void main(String args[]){
             Scanner myScanner = new Scanner(System.in);			//Scanner to read user input
             Random myRandom = new Random();							//Random # generator		
          
             String player1, player2, goesFirst, goesSecond;		//Declare variables
             int goesFirstGuess, goesSecondGuess, randomNumber;				
             int exitCode = 1; 											//Exit Code to terminate program
          
             while(exitCode==1){											//Collect user information
                System.out.println("Please enter player 1's first name:"); 	
                player1 = myScanner.nextLine();
                System.out.println("Please enter player 2's first name:");
                player2 = myScanner.nextLine();
                System.out.println(player1 + " vs. " + player2);
             
                if(player1.compareToIgnoreCase(player2) < 0){	//Determine who goes first alphabetically
                   System.out.println(player1 + " goes first. Please pick a number between 1-10:");
                   goesFirst = player1;
                   goesSecond = player2;
                }
                else if(player1.compareToIgnoreCase(player2) == 0){
                   System.out.println("You have the same name! Did you know this!?");
                   System.out.println(player1 + "1, Please pick a number between 1-10");
                   goesFirst = player1 + "1";
                   goesSecond = player2 + "2";
                }
                else{
                   System.out.println(player2 + " goes first. Please pick number between 1-10:");
                   goesFirst = player2;
                   goesSecond = player1;
                }
             
                goesFirstGuess = myScanner.nextInt();				//Store each players guess
                System.out.println(goesSecond + ", Please pick your number between 1-10");
                goesSecondGuess = myScanner.nextInt();
                System.out.println("Thank you both, please be patient while I determine the winner...");
             
              
                try{															//Delay = Suspense! DUN DUN DUNN
                   Thread.sleep(4000);  
                }
                   catch (InterruptedException ie){
                      System.out.println(ie.getMessage());
                   }
             
             
                randomNumber = myRandom.nextInt(10)+1;				//Generate a Random # between 1-10
                System.out.println(); System.out.println();		//Filler Space
                System.out.println("The random number is " + randomNumber + ",");
             
             
             
             																	//Determine & Report the winner :)
                if(Math.abs((randomNumber-goesFirstGuess)) == Math.abs((randomNumber-goesSecondGuess))){
                   System.out.println("It's a tie!");
                }			
                else if(Math.abs((randomNumber-goesFirstGuess))<Math.abs((randomNumber-goesSecondGuess))){
                   System.out.println(goesFirst + " IS THE WINNER!");
                }			
                else{
                   System.out.println(goesSecond + " IS THE WINNER!");
                }		   
              
                System.out.println(); System.out.println();
                System.out.println("Would you like to play again?");		
                System.out.println("Please type a 0 if you would like to quit, or a 1 if you would like to continue:");
                exitCode = myScanner.nextInt();						//Set flag to play again or exit
                System.out.println();
             
             
             }
             System.out.println("Thanks For Playing! GOODBYE!");//Terminate
          }
       }

    OUTPUT

    Please enter player 1's first name:
    A
    Please enter player 2's first name:
    B
    A vs. B
    A goes first. Please pick a number between 1-10:
    1
    B, Please pick your number between 1-10
    5
    Thank you both, please be patient while I determine the winner...


    The random number is 3,
    It's a tie!


    Would you like to play again?
    Please type a 0 if you would like to quit, or a 1 if you would like to continue:
    1

    Please enter player 1's first name:
    Please enter player 2's first name:
    B
    vs. B
    goes first. Please pick a number between 1-10:
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,696
    Rep Power
    347
    Your problem might be with the Scanner class. It reads the whole line into a buffer.
    Most of the nextXXX() methods read data from the buffer but leave the lineend character in the buffer. The nextLine() method reads everything out of the buffer clearing out the lineend character. If there is only a lineend character in the buffer, that is what nextLine() will read and return as an empty line.
    Before calling nextLine() after a call to nextInt(), you need to call nextLine() to clear the buffer.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Location
    Boynton Beach, FL
    Posts
    2
    Rep Power
    0

    Solved


    Code:
     while(exitCode==1){											                    
                System.out.println("Please enter player 1's first name:"); 	
                player1 = myScanner.nextLine();
                System.out.println("Please enter player 2's first name:");
                player2 = myScanner.nextLine();
                System.out.println(player1 + " vs. " + player2);
    
    ...
    ...
    ...
    
                System.out.println(); System.out.println();
                System.out.println("Would you like to play again?");		
                System.out.println("Please type a 0 if you would like to quit, or a 1 if you would like to continue:");
                exitCode = myScanner.nextInt();				
                myScanner.nextLine();

    Thank you for your help!
    Adding
    myScanner.nextLine();
    like you suggested did indeed clear the buffer and allow the while() loop to reset as planned.

    Thanks again.

IMN logo majestic logo threadwatch logo seochat tools logo