JAVA problem with looping

  • Java
  • Thread starter BrandNewDay
  • Start date
  • #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:
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');
 

Answers and Replies

  • #2
I like Serena
Homework Helper
6,577
176
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:
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');
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.
 
  • #3
harborsparrow
Gold Member
555
120
I'd either use the Scanner object or a BufferedReader. But if not, you probably need to Flush the input buffer in there somewhere.
 

Related Threads on JAVA problem with looping

Replies
2
Views
856
Replies
2
Views
2K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
2
Views
5K
Replies
8
Views
2K
Replies
4
Views
2K
Replies
2
Views
705
  • Last Post
Replies
2
Views
4K
  • Last Post
Replies
2
Views
2K
Top