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

后端 未结 3 1322
小鲜肉
小鲜肉 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:17

    Because when you print char and press Enter you produce 3 symbols (on Windows): character, carriage return and line feed:

    q\r\n
    

    You can find more details here: http://en.wikipedia.org/wiki/Newline

    For your task you may want to use higher level API, e.g. Scanner:

        Scanner scanner = new Scanner(System.in);
        do {
            System.out.println("Guess the letter");
            ch = scanner.nextLine().charAt(0);
        } while (ch != 'q');
    

提交回复
热议问题