Java Scanner 不会“完成"读取输入 [英] Java Scanner won't "finish" reading input

查看:36
本文介绍了Java Scanner 不会“完成"读取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 java 的 Scanner 类时遇到了问题.我可以让它很好地读取我的输入,但问题是当我想输出一些东西时.给定多行输入,当所有输入都被完全读取时,我只想打印一行.这是我用于读取输入的代码:

I've been having trouble using java's Scanner class. I can get it to read my input just fine, but the problem is when I want to output something. Given multiple lines of input, I want to print just ONE line when all the input has been read completely. Here's the code I use for reading input:

    public static void main(String[] args){
    Scanner scanner = new Scanner(System.in);   //scanner reads block of input
    while(scanner.hasNextLine()){    
        //body of loop goes here
        String s = scanner.nextLine();
        Scanner ls = new Scanner(s);   //scanner to parse a line of input
        while(ls.hasNext()){
        //body of nested loop goes here
        ls.next();
        }
    }
    System.out.println("Fin");
    }

即使读取了所有输入行,程序也不会到达 System.out.println 消息.(请注意,消息不能传到其他任何地方,否则它将输出与循环运行的次数一样多).我该如何解决?任何帮助将不胜感激.

Even when all lines of input have been read, the program doesn't reach the System.out.println message. (Note that the message can't go anywhere else or it will output as many times as the loop is run). How do I fix this? Any help would be greatly appreciated.

推荐答案

魔力

Scanner scanner = new Scanner(System.in);
    while(scanner.hasNextLine()){ 

是否永远不会停止从系统输入(除非您使用 ctrl+d 关闭输入(对于 macs)).

Is that there will never stop being input from System (unless you close the input with ctrl+d (for macs)).

为了停止循环,我建议在条件中抛出更多的东西,而不仅仅是 hasNextLine().

To stop the loop, I suggest throw something more in the condition than just hasNextLine().

例如

Scanner scanner = new Scanner(System.in);   //scanner reads block of input
    int BLOCK_SIZE  =3,count=1;
    while(scanner.hasNextLine() && count++ <= BLOCK_SIZE){   //<- Use count here.
        //body of loop goes here
        String s = scanner.nextLine();
        Scanner ls = new Scanner(s);   //scanner to parse a line of input
        while(ls.hasNext()){
        //body of nested loop goes here
        ls.next();
        }
    }
    System.out.println("Fin");

}

这篇关于Java Scanner 不会“完成"读取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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