Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

JAVA problem with looping

  1. Mar 10, 2012 #1
    I don't know why in the main method, the do-while loop won't work the way it's supposed to.
    For instance, if the user types in y, the first loop would execute and then since the value of choice is still 'y', it's supposed to loop again. But instead, it just displays "TOSS COIN? Press y for yes." without asking for a new value of choice. What's wrong with it?

    Code (Text):

    do{
                System.out.print("TOSS COIN? Press y for yes.");
                choice = (char)System.in.read();
                if(choice == 'y' || choice == 'Y')
                {
                    Coins c = Coins.flip();
                    System.out.println(c);
                    if(c == Coins.HEAD)
                        heads++;
                    else
                        tails++;
                }
            }while(choice == 'y' || choice == 'Y');

     
     
  2. jcsd
  3. Mar 10, 2012 #2

    I like Serena

    User Avatar
    Homework Helper

    Welcome to PF, BrandNewDay! :smile:

    Did you press the [Enter] key after pressing 'y'?

    When you call System.in.read() you do not get just one character, but you get a line of characters of which you only read the first one.
    As it is, you automatically get the second choice, which is the [Enter] character.
     
  4. Mar 12, 2012 #3

    harborsparrow

    User Avatar
    Gold Member

    I'd either use the Scanner object or a BufferedReader. But if not, you probably need to Flush the input buffer in there somewhere.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: JAVA problem with looping
  1. Problem in loops (Replies: 14)

Loading...