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();
}
}
我的意思是把Scanner放在外部,然后每个方法输入时候都调用,如果普通循环都会返回让重新输入,但是有抛出异常的循环,抛出异常后就陷入无尽循环了,不会再让你输入信息了。
因为在方法体中定义的只在该方法体中有效啊