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):

                System.out.print("TOSS COIN? Press y for yes.");
                choice = (char)System.in.read();
                if(choice == 'y' || choice == 'Y')
                    Coins c = Coins.flip();
                    if(c == Coins.HEAD)
            }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


    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook