Why my method being called 3 times after System.in.read() in loop

后端 未结 3 1349
小鲜肉
小鲜肉 2020-12-12 01:46

I have started to learn Java, wrote couple of very easy things, but there is a thing that I don\'t understand:

public static void main(String[] args) throws          


        
3条回答
  •  心在旅途
    2020-12-12 02:08

    As has been mentioned, the initial read command takes in 3 characters and holds them in the buffer.

    The next time a read command comes around, it first checks the buffer before waiting for a keyboard input. Try entering more than one letter before hitting enter- your method should get called however many characters you entered + 2.

    For an even simpler fix:

    //add char 'ignore' variable to the char declaration
    char ch ignore;
    
    //add this do while loop after the "ch = (char) System.in.read();" line
    do{
        ignore = (char) System.in.read();
    } while (ignore != '\n');
    

    this way 'ignore' will cycle through the buffer until it hits the newline character in the buffer (the last one entered via pressing enter in Windows) leaving you with an fresh buffer when the method is called again.

提交回复
热议问题