BufferReader读取空行 [英] BufferReader reading empty lines

查看:79
本文介绍了BufferReader读取空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按Enter键,我正在从输入(IDE eclipse Luna)输入行,光标一直向下移动,但没有输出。在尝试的第二种方法中,但是我必须按两次Enter键以打印输出,我该如何解决这两个错误。为什么在第二种方法中,一旦检测到空白行,它就不会打印,为什么我必须按两次Enter键,然后在控制台中按Enter键时会执行什么命令

I am entering lines from input (IDE eclipse Luna) on pressing enter the cursor keeps moving down but no output shows up. In tried second method but i have to press enter twice to print output how can i fix both errors . Why in second method as soon as it detects blank line it doesn't print why i have to press enter twice And what commands goes when we press enter in console

第一方法

private static String para = null;
public static void main(String[] args) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(System.in));
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        para = para + line;
    }
    bufferedReader.close();
    System.out.println(para);
}

第二种方法

String line;
    while (!(line = br.readLine()).equals("")) {
        s1 = line.split(" ");
        for (int j = 1; j < s1.length; j++) {
            int m = Integer.parseInt(s1[j]);
            edges[Integer.parseInt(s1[0]) - 1].add(vertices[m - 1]);
        }

    }


推荐答案


Method1 永远不会结束,因为readLine()永远不会返回null,在从控制台输入中读取时,它将始终返回空String。

Method1 is not going to end ever as below readLine() will never returns null, it will always return empty String while reading from console input.

while((line = bufferedReader.readLine())!= null){
para = para + line;
}

记住,按回车java会将其视为newLine()命令,该命令肯定不为null,因此程序继续运行

Remember on pressing enter java considers it as newLine() command, which surely not null, so your program goes on with empty string and never terminates from the while loop.

我建议使用一些有意义的完整检查来终止while循环。您可以尝试使用Scanner而不是BufferedReader,因为它提供了许多实用方法。

在Scanner中,您可以使用hasNext()这样的方法, hasNextLine()等告诉您是否有进一步的输入。类似的方法,如nextLine(),nextInt(),nextDouble(),可以从命令行或任何其他流中获取特定的转换值。

Method2 正在执行很多不属于Method1的操作,请您共享相同的完整可运行代码。我再次怀疑终止循环的逻辑。

Method2 is doing lot of operations which were not part of the Method1, can you please share full runnable code for the same. I doubt on the logic again for terminating the loop.

因此,我建议在循环访问某些数据时使用更具体的检查来终止循环。

So I would suggest to use more specific check to terminate your loop while iterating through some data.

这篇关于BufferReader读取空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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