问题描述
在我看来,您想跳过所有内容,直到获得整数。此代码在这里跳过除整数以外的所有输入。
只要没有可用的整数(而(!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.");
}
}
解决方法
我一直在试图阻止例外,但我不知道怎么办。我尝试过parseInt
,java.util.NormalExceptionMismatch
等等。
有谁知道如何解决此问题?由于复制和粘贴,格式化有些偏离。
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)