private static void method1(ArrayList<String> list) {
boolean flag = true;
Scanner sc = new Scanner(System.in);
int key;
while (flag) {
System.out.println("--------KTV点歌系统--------");
System.out.println("\t\t1.添加歌曲");
System.out.println("\t\t2.置顶歌曲");
System.out.println("\t\t3.上移歌曲");
System.out.println("\t\t4.退出系统");
System.out.print("\t\t请选择(1-4):");
try {
key = sc.nextInt();
} catch (InputMismatchException E) {
key = 0;
}
switch (key) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
flag = false;
break;
default:
System.out.println("输入有误");
break;
}
}
sc.close();
}
这样子的话捕获到异常后会一直死循环显示输入有误
但是每次在try中newScanner的对象就不会无限循环自动输入一个异常的nextInt
try {
Scanner sc = new Scanner(System.in);
key = sc.nextInt();
sc.close();
} catch (InputMismatchException E) {
key = 0;
}
有没有大佬解下惑