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

新手上路,请多包涵

程序如下:

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

阅读 1.7k
1 个回答

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题