如何使用hasNextInt()来捕获异常?我需要Int,但如果输入是字符,那就是坏的 [英] How can I use hasNextInt() to catch an exception? I need Int but if input is character, that is bad
问题描述
我一直在试图阻止例外,但我无法弄清楚如何。
我试过 parseInt
, java.util.NormalExceptionMismatch
等。
I have been trying to stop the exceptions but I cannot figure out how.
I tried parseInt
, java.util.NormalExceptionMismatch
etc.
有谁有任何洞察力如何解决这个问题?格式化由于复制和粘贴而有点偏差。
Does anyone have any insight how to fix this problem? Formatting is a bit off due to copy and paste.
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
if (!intFind.hasNextInt())
intFind.next();
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
}
}while(select < 0)
尝试:
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
{
try{
select = intFind.nextInt();
}catch (java.util.InputMismatchException e)
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
return;
}
}
}while(select < 0)
推荐答案
在我看来,你想跳过一切,直到你得到一个整数。这里的代码跳过除整数之外的任何输入。
It seems to me that you want to skip everything until you get an integer. This code here skips any input except an integer.
只要没有整数可用(while(!in.hasNextInt()))丢弃可用的输入(in.next)。当整数可用时 - 读它(int num = in.nextInt();)
As long as there is no integer available (while (!in.hasNextInt())) discard the available input (in.next). When integer is available - read it (int num = in.nextInt();)
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (!in.hasNextInt()) {
in.next();
}
int num = in.nextInt();
System.out.println("Thank you for choosing " + num + " today.");
}
}
这篇关于如何使用hasNextInt()来捕获异常?我需要Int,但如果输入是字符,那就是坏的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!