Java扫描程序不会“完成"操作.阅读输入 [英] Java Scanner won't "finish" reading input

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

问题描述

我在使用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扫描程序不会“完成"操作.阅读输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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