我一直在尝试阻止异常,但我不知道如何阻止。
我试过parseInt
, java.util.NormalExceptionMismatch
etc.
有谁知道如何解决这个问题?由于复制和粘贴,格式有点不对。
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)
在我看来,你想跳过一切,直到得到一个整数。此代码此处跳过除整数之外的任何输入。
只要没有可用的整数(while (!in.hasNextInt()))就丢弃可用的输入(in.next)。当整数可用时 - 读取它 (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.");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)