通过Java控制台获取输入
我经常参加编程比赛,其中最重要的部分是从用户那里获取输入,因为我们通常使用两种东西通过Java控制台获取输入,java,Java,我经常参加编程比赛,其中最重要的部分是从用户那里获取输入,因为我们通常使用两种东西 缓冲读取器 扫描器 现在的问题是,有时上述每一项在输入时都会出现以下错误 1.空指针异常 2.NoTouchElementFoundException 下面是两者的代码 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine());
- 缓冲读取器
- 扫描器
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所说,可能流已经关闭了。这更像是在使用调试器处理示例时问自己的问题。