问答

循环调用标准输入流从键盘获取数据时只能执行一次

作者:admin 2021-07-09 我要评论

程序如下: public class ExamView{ public char getUserAction() { BufferedReader bufferedReader = null; String string = null; try { bufferedReader = new...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

程序如下:

public class ExamView
{
    public char getUserAction()
    {
        BufferedReader bufferedReader = null;
        String string = null;
        try
        {
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Please input your answer:");
            string = bufferedReader.readLine().substring(0,1);
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (string != null)
                    bufferedReader.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        switch (string.toUpperCase())
        {
            case "A":
                return 'A';
            case "B":
                return 'B';
            case "C":
                return 'C';
            case "D":
                return 'D';
            case "N":
                return 'N';
            case "P":
                return 'P';
        }
        return ' ';
    }
}
public class Exam
{
    public static void main(String[] args)
    {

        ExamView examView = new ExamView();
        while (true)
        {
            char a = examView.getUserAction();
            System.out.println(a);
        }
    }

我想通过while循环来多次获取从键盘输出的选择并输出,但是这个循环运行到第二次时会报错,错误提示是流被关闭了,但每次循环不都会先创建一个输入流吗?求解答。(下面是错误提示)
image.png

###

System.in是一个特殊的 InputStream,因为系统来维护他的打开和关闭,所以不要使用 close 方法关掉,关掉了就没法再读取了。

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • elementUI表单Object.assign处理后无法

    elementUI表单Object.assign处理后无法

  • nacos作为配置中,有时可以加载到配置

    nacos作为配置中,有时可以加载到配置

  • font-spider压缩字体后,文件大小没有

    font-spider压缩字体后,文件大小没有

  • Vue SSR babel node_modules中的一个包

    Vue SSR babel node_modules中的一个包

腾讯云代理商
海外云服务器