Search code examples
javainputconsolebuffered

BufferedReader error in loop


The first time this loop iterates works well but after I press the char 'y' in order to repeat, the next time it shows, it won't let me enter another name. I don't know what may be causing this, but it reminds me of C when you need to clear the input buffer.

Any help will be certainly appreciated.

byte counter = 1;
boolean myCondition = false;
List<String> myList = new ArrayList();
BufferedReader objReader = new BufferedReader(new InputStreamReader(System.in));

do{
    System.out.println("Enter the #" +counter +" person's name:");
    // low quality validation
    String dude = objReader.readLine();

    while (myList.contains(dude)){
        System.out.println("Man, this dude:" +dude +" is already loaded into the List! Pick another name:\n");
        dude = objReader.readLine();            
    }

    myList.add(dude);
    counter++;
    System.out.println("Would you like to add another name to the list? yes/no");

    char myChar = (char) System.in.read();

    if (myChar == 'y' || myChar == 'Y')
        myCondition = true;
    else
        myCondition = false;

    } while (myCondition);

Solution

  • Look at your code:

    1. You read character 'y'
    2. The char myChar = (char) System.in.read(); waits until you press Enter
    3. myChar is now 'y'. This leaves '\n' (`Enter') in buffer
    4. Next String dude = objReader.readLine(); reads line ended by '\n' that is present already in buffer.

    You should read whole line instead simple read()

    If you want better resolution of y:

    String line = objReader.readLine();
    myCondition = line.startsWith("Y") || line.startsWith("y");