绝对经典代码!
package com.imooc;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
inputCommand();
}
public static void inputCommand(){
String[] Books = {"高数","英语","化学"};
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
Scanner sc = new Scanner(System.in);
try{
int flag = sc.nextInt();
if(flag == 1){
}
if(flag == 2){
inputNum();
}
//如果输入数字大于2,与异常处理相同
if(flag>2){
System.out.println("命令输入错误!请根据提示重新输入命令!");
inputCommand();
}
}catch(Exception e){ //输入字符,程序执行catch语句块代码
System.out.println("命令输入错误!请根据提示重新输入命令!");
inputCommand(); //循环
}
}
//按照名称查找图书的方法
public static void inputName(){
String[] Books = {"高数","英语","化学"};
System.out.println("输入图书名称:");
Scanner sc = new Scanner(System.in);
try{
String name = sc.next();
System.out.println("book:"+name);
inputCommand(); //继续查找图书
}catch(Exception e){
System.out.println("图书不存在!");
inputCommand();
}
}
//按照序号查找图书的方法
public static void inputNum(){
String[] Books = {"高数","英语","化学"};
System.out.println("输入图书序号:");
Scanner sc = new Scanner(System.in);
try{
int num = sc.nextInt();
System.out.println("book:"+Books[num]);
inputCommand(); //继续查找图书
}catch(Exception e){
System.out.println("图书不存在!");
inputCommand();
}
}
}