James Guy
James Guy

Reputation: 21

Why output keeps same many output?

boolean yn = true;
        while(yn)
        {
            System.out.println("please enter your name");
            char name = (char) System.in.read();
            switch(name)
            {
                case 'y':
                    yn = false;
                    break;
                case 'Y':
                    yn = false;
                    break;
                case 'n':
                    yn = false;
                    break;
                case 'N':
                    yn = false;
                    break;
                default:
                    System.out.println("You did not input a correct choice");
            }

When I enter other keys than y or n, more than one of same output keeps coming out. Any suggestions? I want to see only one output, and System.in.read() is a must. Not scanner.

Upvotes: 1

Views: 61

Answers (3)

danielctw
danielctw

Reputation: 83

This is my take on this. Using Scanner class instead.

Scanner scanner = new Scanner (System.in);
System.out.println("please enter your name");
char name = scanner.next().charAt(0);

Mine I would get the first character entered instead.

Upvotes: 0

someone
someone

Reputation: 132

The reason of infinite loop is you read input from System.in.read() and cast it into char.

System.in.read() will return code -1 when the end of input stream. If you cast it into char the value will be 65535.

So, please add this piece of code after: char name = (char) System.in.read();

System.out.println("name="+name);
char next = (char)System.in.read();
if(next==65535)
    break;

This code works for me. https://ideone.com/ppk3Fi

Upvotes: 0

Jordan
Jordan

Reputation: 2283

You're using System.in.read() to read in the next character, but when you type a character and hit enter, you're actually entering three characters: The character you typed, a carriage return character ('\r'), and a newline character ('\n'). I assume you're on a Mac, because Windows machine just use the newline character.

Since you're inside of a while loop, it keeps reading until you hit a valid character that sets yn to true.

You might consider using a Scanner to make this easier.

Upvotes: 2

Related Questions