Java Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesJava Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old October 5th, 2012, 03:36 PM
johnsonj561 johnsonj561 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2012
Location: Boynton Beach, FL
Posts: 2 johnsonj561 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 23 m 9 sec
Reputation 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:

Reply With Quote
  #2  
Old October 5th, 2012, 05:02 PM
NormR's Avatar
NormR NormR is offline
Contributing User
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Aug 2010
Location: SW Missouri
Posts: 2,955 NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level)NormR User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Week 6 Days 2 h 53 m 34 sec
Reputation Power: 345
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.

Reply With Quote
  #3  
Old October 5th, 2012, 05:30 PM
johnsonj561 johnsonj561 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2012
Location: Boynton Beach, FL
Posts: 2 johnsonj561 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 23 m 9 sec
Reputation 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.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesJava Help > While loop not carrying out the way I'd like

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap