java.util.Scanner不返回到提示 [英] java.util.Scanner does not return to Prompt

查看:31
本文介绍了java.util.Scanner不返回到提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            System.out.println(s.next());
        }
        s.close();
    }
}

此程序不会返回提示(我已经通过终端运行了它).这是为什么?我该如何纠正?

This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?

推荐答案

此程序不会返回提示(我已经通过终端运行了该程序).为什么会这样?

This program does not return to prompt (I have been running it through the Terminal). Why is that?

因为s.hasNext()将阻塞直到有更多输入可用,并且仅在遇到流结束时才返回false.

Because s.hasNext() will block until further input is available and will only return false if it encounters end of stream.

从文档中

如果该扫描仪的输入中包含另一个令牌,则返回true. 此方法在等待输入扫描时可能会阻塞.

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan.

在Unix系统上,您可以通过键入 Ctrl + D 结束流,它可以正确地将控制权返回给提示符,(或通过键入终止整个程序Ctrl + C ).

On a unix system you can end the stream by typing Ctrl+D which correctly returns control to the prompt, (or terminate the whole program by typing Ctrl+C).

我该如何纠正?

How can I correct it?

您可以

  • 按照JJ的建议,保留一些用于终止程序的输入字符串,或者
  • 您可以依靠用户使用Ctrl + D关闭输入流,也可以
  • 在try/catch中将循环括起来,然后让另一个线程中断主线程,然后该线程正常退出.
  • 以编程方式从另一个线程执行System.in.close().
  • reserve some input string used for terminating the program, as suggested by JJ, or
  • you could rely on the user closing the input stream with Ctrl+D, or you could
  • enclose the loop in a try/catch and let another thread interrupt the main thread which then exits gracefully.
  • do System.in.close() programatically from another thread.

这篇关于java.util.Scanner不返回到提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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