为什么我的方法在System.in.read()循环后被调用3次 [英] Why my method being called 3 times after System.in.read() in loop

查看:53
本文介绍了为什么我的方法在System.in.read()循环后被调用3次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习Java,写了一些非常简单的东西,但是有些事情我不理解:

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 java.io.IOException
{
    char ch;

    do 
    {
        System.out.println("Quess the letter");
        ch = (char) System.in.read();
    }
    while (ch != 'q');
}

为什么在给出错误答案后, System.out.println 会打印三遍问字母".在给出任何答案字符串之前,只打印一次.

Why does the System.out.println prints "Quess the letter" three times after giving a wrong answer. Before giving any answer string is printed only once.

预先感谢

推荐答案

因为当您打印char并按 Enter 时,会产生3个符号(在Windows上):字符,回车符和换行符:

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

q\r\n

您可以在此处找到更多详细信息: http://en.wikipedia.org/wiki/Newline

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

对于您的任务,您可能需要使用更高级别的API,例如扫描器:

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');

这篇关于为什么我的方法在System.in.read()循环后被调用3次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆