输入错误类型时如何防止扫描程序抛出异常?
这是一些示例代码:
import java.util.Scanner;
class In
{
public static void main (String[]arg)
{
Scanner in = new Scanner (System.in) ;
System.out.println ("how many are invading?") ;
int a = in.nextInt() ;
System.out.println (a) ;
}
}
如果我运行该程序并给它一个像 4
这样的 int
,那么一切都会顺利。
另一方面,如果我回答太多
,它就不会嘲笑我的笑话。相反,我得到了这个(如预期的那样):
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:819)
at java.util.Scanner.next(Scanner.java:1431)
at java.util.Scanner.nextInt(Scanner.java:2040)
at java.util.Scanner.nextInt(Scanner.java:2000)
at In.main(In.java:9)
有没有办法让它忽略不是整数的条目或重新提示“有多少正在入侵?”我想知道如何做到这两点。
Here's some sample code:
import java.util.Scanner;
class In
{
public static void main (String[]arg)
{
Scanner in = new Scanner (System.in) ;
System.out.println ("how many are invading?") ;
int a = in.nextInt() ;
System.out.println (a) ;
}
}
If I run the program and give it an int
like 4
, then everything goes fine.
On the other hand, if I answer too many
it doesn't laugh at my funny joke. Instead I get this(as expected):
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:819)
at java.util.Scanner.next(Scanner.java:1431)
at java.util.Scanner.nextInt(Scanner.java:2040)
at java.util.Scanner.nextInt(Scanner.java:2000)
at In.main(In.java:9)
Is there a way to make it ignore entries that aren't ints or re prompt with "How many are invading?" I'd like to know how to do both of these.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
Scanner
具有的众多hasNext*
方法之一进行预验证。这甚至可以防止抛出
InputMismatchException
,因为在读取它之前,您始终要确保它将匹配。java.util。扫描仪 API
boolean hasNextInt()
:如果此扫描仪输入中的下一个标记可以解释为 int 值,则返回true
使用nextInt()
方法的默认基数。 扫描仪不会前进超过任何输入。String nextLine()
:使扫描仪前进超过当前行并返回输入被跳过。请记住粗体部分。
hasNextInt()
不会超越任何输入。如果它返回true
,您可以通过调用nextInt()
来推进扫描器,这不会抛出InputMismatchException
。如果它返回
false
,那么您需要跳过“垃圾”。最简单的方法就是调用nextLine()
,可能两次,但至少一次。为什么您可能需要执行两次
nextLine()
,原因如下:假设这是输入的输入:假设扫描仪位于该输入的开头。
hasNextInt()
为 true,nextInt()
返回42
;扫描仪现在位于第一个[enter]
之前。hasNextInt()
为 false,nextLine()
返回空字符串,第二个nextLine()
返回“太多!”< /代码>;扫描仪现在位于第二个
[enter]
之后。hasNextInt()
为 true,nextInt()
返回0
;扫描仪现在位于第三个[enter]
之前。这是将其中一些内容组合在一起的示例。您可以尝试使用它来研究
Scanner
的工作原理。假设输入是:
那么输出的最后一行是:
You can use one of the many
hasNext*
methods thatScanner
has for pre-validation.This prevents
InputMismatchException
from even being thrown, because you always make sure that it WILL match before you read it.java.util.Scanner API
boolean hasNextInt()
: Returnstrue
if the next token in this scanner's input can be interpreted as an int value in the default radix using thenextInt()
method. The scanner does not advance past any input.String nextLine()
: Advances this scanner past the current line and returns the input that was skipped.Do keep in mind the sections in bold.
hasNextInt()
doesn't advance past any input. If it returnstrue
, you can advance the scanner by callingnextInt()
, which will not throw anInputMismatchException
.If it returns
false
, then you need to skip past the "garbage". The easiest way to do this is just by callingnextLine()
, probably twice but at least once.Why you may need to do
nextLine()
twice is the following: suppose this is the input entered:Let's say the scanner is at the beginning of that input.
hasNextInt()
is true,nextInt()
returns42
; scanner is now at just before the first[enter]
.hasNextInt()
is false,nextLine()
returns an empty string, a secondnextLine()
returns"too many!"
; scanner is now at just after the second[enter]
.hasNextInt()
is true,nextInt()
returns0
; scanner is now at just before the third[enter]
.Here's an example of putting some of these things together. You can experiment with it to study how
Scanner
works.Let's say the input is:
Then the last line of the output is:
总的来说,我真的非常不喜欢使用相同的库调用来进行读取和解析。语言库似乎非常不灵活,而且常常无法按照您的意愿行事。
从 System.in 提取数据的第一步应该不会失败,因此将其作为字符串读取到变量中,然后将该字符串变量转换为 int。如果转换失败,那就太好了——打印您的错误并继续。
当你用可能引发异常的东西包装你的流时,整个混乱让你的流处于什么状态会有点令人困惑。
In general I really, really dislike using the same library call for both reading and parsing. Language libraries seem to be very inflexible and often just can't be bent to your will.
The first step that pulls data from System.in should not be able to fail, so have it read it as a string into a variable, then convert that string variable to an int. If the conversion fails, great--print your error and continue.
When you wrap your stream with something that can throw an exception, it gets kind of confusing just what state the whole mess leaves your stream in.
当错误发生时让应用程序抛出错误总是比阻止错误发生的方法更有好处。
一种替代方法是将代码包装在
try {...}
catch {...}
块中以处理InputMismatchException
。您可能还希望将代码包装在
while
循环中,以使Scanner
不断提示,直到满足特定条件。It's always a benefit to have your application throw an error when an error occurs opposed to ways to keep it from happening.
One alternative is to wrap the code inside a
try {...}
catch {...}
block forInputMismatchException
.You might also want to wrap the code inside a
while
loop to have theScanner
keep prompting until a specific condition is met.