我有一个关于数据验证和扫描仪的问题.以下代码检查userinput.不允许使用除整数之外的任何内容,并要求用户重新输入值.我的问题是代码仅在扫描程序是在while循环中声明.如果扫描仪在外面声明,程序将无限执行.为什么?谢谢.
int UserInp;
boolean dataType=false;
while(dataType==false)
{
Scanner sc=new Scanner(System.in);
try
{
System.out.print("\nEnter a number: ");
UserInp=sc.nextInt();
dataType=true;
}
catch(Exception JavaInputMismatch)
{
System.out.println("Option not available.Try again.");
}
}
Run Code Online (Sandbox Code Playgroud)