Java 什么';从用户那里获取输入的众多方法之间的区别是什么?

Java 什么';从用户那里获取输入的众多方法之间的区别是什么?,java,Java,以以下基本程序为例: import java.util.Scanner; public class Practice { public static void main(String[] args) { char userInput; String convertString; do { System.out.println("Here are your choices:");

以以下基本程序为例:

import java.util.Scanner;

public class Practice 
{
    public static void main(String[] args)  
    {
        char userInput;
        String convertString;

        do 
        {
            System.out.println("Here are your choices:");
            System.out.println("A. \nB. \nC. \nD.");

            Scanner kbd = new Scanner(System.in);
            convertString = kbd.next();
            userInput = convertString.charAt(0);

            switch(userInput)
            {
            case 'A':
                System.out.println("You have chosen A!");
                break;
            case 'B':
                System.out.println("You have chosen B!");
                break;
            case 'C':
                System.out.println("You have chosen C!");
                break;
            case 'D':
                System.out.println("You have chosen D! This program will now terminate.");
                break;
            default:
                System.out.println("Sorry, you have to make a selection.");
            }
        } while (userInput > 'D');

    }
}
它工作得非常好。 但是,如果我使用System.in.read()版本而不是Scanner版本,我的程序将在允许我进行选择之前循环3次。 为什么会发生这种情况?我如何修复它

由于我来自C/C++背景,我假设这是因为输入流中存在“遗留”字符,当程序循环而不允许我键入所需输入时,它将“清除”流。但如果这是真的,为什么它会循环3次而不是一次(因为要清除\n,您只需要从输入流中获取另一个剩余字符)

最后,哪种方法最好/更常用


谢谢

使用
System.in.read()
时,程序会循环三次,因为在Windows上,行分隔符是两个字符:回车符后跟换行符,或
“\r\n”

在Unix系统(Mac OS X、Linux、Solaris等)上,行分隔符是单行馈送
\n

您可以通过包装
系统来解决此问题。在
中,阅读整行内容,或者更好地使用或类,或者根据一些人的说法,最好使用图形用户界面

使用旧方法的示例如下:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = in.readLine();
使用
控制台
类的示例:

Console con = System.console();
String line = con.readLine();

<>代码>系统。在中是一个<代码>输入流< /代码>,它是一个相当低级别的流类,类似于代码> STD::StRuBuf在C++中或<代码> Frad C.中,它允许您读取单个字节和固定大小的字节数组。要使用它做一些有用的事情,你应该将它包装在一个
BufferedReader
中,它提供了一个
readLine()
方法。

System.in基于的方法被贬低了,不要使用它,这很糟糕,他们意识到这很糟糕,他们给了我们扫描仪,我们很高兴System.in.read()从输入流中读取一个字节。尝试将其包装在InputStreamReader中,并读取整行。@Richardingle:
系统。在
中,它没有被弃用,而且也不错,只是不适合此工作。他们意识到缺少正确的工具,这就是为什么添加了
扫描仪
。@RichardTingle你确定吗?我很确定输入流的每个包装器都必须使用
InputStream.read
。可能有点夸张,它的直接用法不再是使用InputStreamReader了,对吧?数据在发送到java程序之前由控制台进行缓冲
InputStreamReader
类没有
readLine
方法,但它是创建BufferedReader的中间步骤。出于某种原因,我认为InputStreamReader可以读取行。哦,好吧