Scanner类是在循环体之外初始化,你第一次输入的数据没有清空,return sc.nextInt不会等你再输入新的数据,所以你输入3.1这样非法数据以后的每次getInt都返回3.1,
public static Integer scan()
{
Scanner sc=new Scanner(System.in);
while(true)
{
try
{
return sc.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("请输入数字!");
System.out.print("重新输入(如需退出请按ctrl+z):");
}
catch(NoSuchElementException e)
{
return null;
}
}
}