Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过Java控制台获取输入_Java - Fatal编程技术网

通过Java控制台获取输入

通过Java控制台获取输入,java,Java,我经常参加编程比赛,其中最重要的部分是从用户那里获取输入,因为我们通常使用两种东西 缓冲读取器 扫描器 现在的问题是,有时上述每一项在输入时都会出现以下错误 1.空指针异常 2.NoTouchElementFoundException 下面是两者的代码 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine());

我经常参加编程比赛,其中最重要的部分是从用户那里获取输入,因为我们通常使用两种东西

  • 缓冲读取器
  • 扫描器
现在的问题是,有时上述每一项在输入时都会出现以下错误 1.空指针异常 2.NoTouchElementFoundException

下面是两者的代码

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());
扫描仪是

Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

有人能解释为什么会发生这种情况吗?

好吧,在一种情况下,您的BufferedReader为null,因此
br.readLine()
会导致NullPointerException

类似地,如果没有这样的下一个元素,则不能调用
sc.nextInt()
,从而导致NoTouchElementException


解决方案:将其包装在try/catch块中。

考虑到可能出现的异常,您可以执行以下简单操作

try
{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int n=Integer.parseInt(br.readLine());
}
catch(NullPointerException nullPE)
{
    //do Whatever it is that you want to do in case of the buffered reader being null.
}
catch (NumberFormatException numFE)
{
        //do Whatever it is that you want to do in case of a number format exception, probably request for a correct input from the user
}
请注意,读卡器正在从控制台读取整行内容,因此您还必须捕获
NumberFormatException

在另一种情况下,您可以简单地使用类似于下面提供的解决方案

try
{
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
}
catch(NoSuchElementException ex)
{
    //do Whatever it is that you want to do if an int was not entered, probably request for a correct input from the user
}

使用异常处理来管理程序中基于用户任意输入的情况是一种很好的做法。

此外,如果流已经关闭,br.readLine()可以返回null。这两个类及其方法的行为都在API文档()中有很好的文档记录,但是当我自己提供输入时,这怎么可能是空的呢?正如@Gus所说,可能流已经关闭了。这更像是在使用调试器处理示例时问自己的问题。