java BufferedReader readLine() 来自标准输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13966448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:35:34  来源:igfitidea点击:

BufferedReader readLine() from standard input

java

提问by Marky0414

I need to read from the standard input. I am not that familiar with BufferedReader and have only used Scanner so far. Scanner (or probably something inside my code) keeps on giving me TLE. Now the problem is that BufferedReader seems to skip some lines and I keep on getting a NumberFormatException.

我需要从标准输入中读取。我对 BufferedReader 不太熟悉,到目前为止只使用过 Scanner。扫描仪(或者可能是我的代码中的某些东西)不断给我 TLE。现在的问题是 BufferedReader 似乎跳过了一些行,我不断收到 NumberFormatException。

Here's my code:

这是我的代码:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    int cases = Integer.parseInt(reader.readLine());

    for(int i = 0; i < cases && cases <= 10; i++) {
        int numLines = Integer.parseInt(reader.readLine());
        String[] lines = new String[numLines + 1];
        HashSet<String> pat = new HashSet<String>();

        for(int j = 0; j < numLines && j <= 10; j++) {
            String l = reader.readLine();

            String patternStr = "\W+";
            String replaceStr = "";

            Pattern pattern = Pattern.compile(patternStr);
            Matcher matcher = pattern.matcher(l.toString());

            String m = matcher.replaceAll(replaceStr);

            lines[j] = m;
            getPatterns(m, pat);

            System.out.println(m);
        }

The error occurs after the second input. Please help.

错误发生在第二次输入之后。请帮忙。

采纳答案by Rohit Jain

BufferedReader#readLine()method does not read the newline character at the end of the line. So, when you call readLine()twice, the first one will read your input, and the second one will read the newlineleft over by the first one.

BufferedReader#readLine()方法不读取行尾的换行符。因此,当您调用readLine()两次时,第一个将读取您的输入,第二个将读取newline第一个的剩余部分。

That is why it is skipping the input you gave.

这就是它跳过您提供的输入的原因。

You can use BufferedReader#skip()to skip the newline character after every readLinein your for loop.

您可以使用BufferedReader#skip()后,每跳过换行符readLine在你的for loop