求教下大神 我如果不把 Scanner input = new Scanner(System.in);在每个方法中都重新定义一下,为什么在异常时候不会让我重新输入,就会陷入无尽循环。
package com.Project3;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public void findBook(){
for(int i = 1;;){
try{
System.out.println("输入命令:1-按照书名查书;2-按照序号查书");
Scanner input = new Scanner(System.in);
int k = input.nextInt();
String name;
if(k == 1){
name = getbookname();
System.out.println("book:"+name);
break;
}
if(k==2){
name = getbooknum();
System.out.println("book:"+name);
break;
}
else {
System.out.println("输入有误");
continue;
}
}catch(InputMismatchException e){
System.out.println("命令输入错误!请根据指令输入数字命令!");
}
catch(Exception e){
System.out.println(e.getMessage());
}
continue;
}
}
public String getbookname() throws Exception{
Scanner in = new Scanner(System.in);
System.out.println("请输入图书名称:");
String name = in.next();
if(name.equals("高数")){
return name;
}else{
throw new Exception("图书不存在!");
}
}
public String getbooknum() throws Exception{
while(true){
System.out.println("请输入图书序号:");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
try{
if(num == 1){
return "数据结构";
}else{
throw new Exception("图书不存在");
}
}catch(InputMismatchException e){
throw new Exception("命令输入错误!请根据指令输入数字命令");
}
}
}
public static void main(String[] args) {
Test c = new Test();
c.findBook();
}
}