Scanner中用nextInt(输入非数字),产生异常后再执行输入时的现象
package test1;
import java.util.Scanner;
public class test {
Scanner cmd = new Scanner(System.in);
String [] bookName = {"高数","数据结构"};
public int inputCommand(){
int command;
try {
command = cmd.nextInt();
return command;
} catch (Exception e) {
cmd = new Scanner(System.in);
return -1;
}
}
public String searchSerial() throws Exception{
System.out.println("输入序号:");
while(true)
{
try {
int serial = cmd.nextInt();
return bookName[serial];
}catch(Exception e) {
// cmd = new Scanner(System.in); //如果注释掉这一行就会发生图中的错误
throw new Exception("图书不存在 s");
}
}
}
public static void main(String[] args) {
test t =new test();
while(true)
{
try {
System.out.println("输入命令,1-按名称查找,2-按序号查找");
int i=t.inputCommand();
switch (i)
{
case 2:
{
System.out.println("book:"+t.searchSerial());
break;
}
case -1:
{
System.out.println("命令输入错误!请根据提示输入数字命令!");
continue;
}
default:
{
System.out.println("命令输入错误!");
continue;
}
}
break;
}catch(Exception e)
{
System.out.println(e.getMessage());
continue;
}
}
}
}注释的那一行cmd = new Scanner(System.in);

取消注释后结果

请大神给我讲讲内部的原理,个人理解是输入的值还被保存着但是不知道为啥在执行一次就没了。。