Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Weird issue with while loop ending/being skipped

  1. #1
    Junior Member
    Join Date
    Nov 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Weird issue with while loop ending/being skipped

    I'm fairly new to Java (and programming in general). I've been getting everything done pretty easily so far but this issue is really frustrating me. I've been through things a thousand different ways and cannot figure out why it's doing this:

    Here is my code:
    import java.util.Scanner;
     
    public class Driver
    {
        public static void main (String args [])
        {
          // Declare and instantiate a new coin object
    		  Dice die1 = new Dice();
            Dice die2 = new Dice();
    		  double account;
    		  double wager;
    		  int total;
            String userReady;
            boolean result;
     
          // Create keyboard object
            Scanner keyboard = new Scanner(System.in);
     
    		// Initial game banner
    	    	System.out.println("Welcome to the game of Simple Craps");
     
    		// Create gambling account for user specified amount
    			System.out.print("How much do you have to gamble? ");
    			account = keyboard.nextDouble();
     
          // Determine if user is ready to play
    			System.out.print("Are you ready to play (Y or N)? ");
    			userReady = keyboard.nextLine();
     
          // Loop while the user wants to continue
            while (userReady.equalsIgnoreCase("Y"))
            {       
     
    		   	// Display totalDollars
    				System.out.println("You have $" + account + " remaining");
     
        	      // Determine how much the user wants to gamble
    				System.out.print("How much would you like to bet? ");
         		   wager = keyboard.nextDouble();
     
    				if (wager <= account && account > 0)
    				{
            		 // Roll the dice
              	    die1.roll();
              		 die2.roll();
     
    				// Retrieve and display results
    					System.out.println("You rolled a " + die1.getDiceValue() + " and a " + 
    		  						die2.getDiceValue() + " for a total of " + die1.add(die2));
     
    						if (die1.add(die2) == 7 || die1.add(die2) == 11)
    							{
    								account += wager;
    								System.out.println("You win $" + wager);
    								System.out.println();
    						 	}
    						else if (die1.add(die2) == 2 || die1.add(die2) == 3 || die1.add(die2) == 12)
    							{
    								account -= wager;
    								System.out.println("You lose $" + wager);
    								System.out.println();
    							}
    						else 
    						   System.out.println("Draw");
    			    } //End if loop
     
     
     
            // Ask user if they want to try again
           		  System.out.println();
      	     	  	  System.out.print("Try again (Y or N)? ");
                  userReady = keyboard.nextLine(); 
     
     
    		   }//End while loop
     
     
     
         }//End main
     
    }//End class

    And the problem is that the "Are you ready to play?" question does not seem to work

    Here is sample output with the above code:

    ----jGRASP exec: java Driver

    Welcome to the game of Simple Craps
    How much do you have to gamble? 123
    Are you ready to play (Y or N)?
    ----jGRASP: operation complete.

    The very weird thing (at least to me), is that if I initialize account to 9.0 and remove the lines:
    		// Create gambling account for user specified amount
    			System.out.print("How much do you have to gamble? ");
    			account = keyboard.nextDouble();

    The program runs and outputs the following:

    Welcome to the game of Simple Craps
    Are you ready to play (Y or N)? y
    You have $9.0 remaining
    How much would you like to bet? 1
    You rolled a 1 and a 1 for a total of 2
    You lose $1.0


    Try again (Y or N)?
    ----jGRASP: operation complete.
    Both are issues with the validation not working, but I'm at a loss as to why. Any ideas? Big thanks in advance, and let me know if you need any more information.
    Last edited by helloworld922; November 10th, 2009 at 01:34 AM.


  2. #2
    Junior Member
    Join Date
    Nov 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Weird issue with while loop ending/being skipped

    I changed the line
    // Ask user if they want to try again
    System.out.println();
    keyboard.nextLine();
    System.out.print("Play again (Y or N): ");
    userReady = keyboard.nextLine();
    that takes place after the while loop, and now it works.

    Somebody else suggested the extra keyboard.nextLine();, which worked. I've used that in the past but I can't remember how you know when/when not to use that. Any general rules to go by? Thanks

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Weird issue with while loop ending/being skipped

    The reason is that the .nextDouble(), .nextInt(), etc. methods don't consume the new-line character. The user will type something like this:

    "123\n" (\n comes from user hitting the return/enter key)

    the .nextDouble() (and related) methods will consume 123, but \n is still left in the buffer. So, when nextLine() or next() is called, they return "" and consume the \n character.

  4. #4
    Junior Member
    Join Date
    Dec 2009
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Weird issue with while loop ending/being skipped

    in my opinion , i dont think so... because the compiler will execute and read sequentially each and every line of your code.. even the smallest space(i think so)...

    so if the compiler encounters anything that IT CANT REACH... it will complain... because it cant reach it..

  5. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Weird issue with while loop ending/being skipped

    That's not true... It's possible to trick the compiler:

    		boolean a = true;
    		while (a)
    		{
    			System.out.println("Infinite loop!");
    		}
    		System.out.println("I tricked the compiler! This code is unreachable");

Similar Threads

  1. ClassNotFoundException (bit weird)
    By chronoz13 in forum Exceptions
    Replies: 1
    Last Post: April 26th, 2011, 02:15 AM
  2. url pattern issue - please help me...
    By bharathik in forum JavaServer Pages: JSP & JSTL
    Replies: 2
    Last Post: November 9th, 2009, 04:28 AM
  3. Repeating program issue
    By Bill_H in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 24th, 2009, 10:58 AM
  4. Issue with JTextField Locking
    By PekinSOFT.Systems in forum AWT / Java Swing
    Replies: 0
    Last Post: October 1st, 2009, 11:12 AM
  5. Issues with Tomcat 6.0
    By sanyog24681 in forum Java Servlet
    Replies: 0
    Last Post: October 21st, 2008, 07:55 AM