絕對(duì)經(jīng)典代碼!
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 = {"高數(shù)","英語(yǔ)","化學(xué)"};
System.out.println("輸入命令:1-按照名稱(chēng)查找圖書(shū);2-按照序號(hào)查找圖書(shū)");
Scanner sc = new Scanner(System.in);
try{
int flag = sc.nextInt();
if(flag == 1){
}
if(flag == 2){
inputNum();
}
//如果輸入數(shù)字大于2,與異常處理相同
if(flag>2){
System.out.println("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示重新輸入命令!");
inputCommand();
}
}catch(Exception e){ //輸入字符,程序執(zhí)行catch語(yǔ)句塊代碼
System.out.println("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示重新輸入命令!");
inputCommand(); //循環(huán)
}
}
//按照名稱(chēng)查找圖書(shū)的方法
public static void inputName(){
String[] Books = {"高數(shù)","英語(yǔ)","化學(xué)"};
System.out.println("輸入圖書(shū)名稱(chēng):");
Scanner sc = new Scanner(System.in);
try{
String name = sc.next();
System.out.println("book:"+name);
inputCommand(); //繼續(xù)查找圖書(shū)
}catch(Exception e){
System.out.println("圖書(shū)不存在!");
inputCommand();
}
}
//按照序號(hào)查找圖書(shū)的方法
public static void inputNum(){
String[] Books = {"高數(shù)","英語(yǔ)","化學(xué)"};
System.out.println("輸入圖書(shū)序號(hào):");
Scanner sc = new Scanner(System.in);
try{
int num = sc.nextInt();
System.out.println("book:"+Books[num]);
inputCommand(); //繼續(xù)查找圖書(shū)
}catch(Exception e){
System.out.println("圖書(shū)不存在!");
inputCommand();
}
}
}
2014-10-28
if(flag==1)括號(hào)里補(bǔ)充inputName();就完美了
2014-09-05
選擇桉書(shū)名查找的時(shí)候沒(méi)做處理啊。。代碼還是不錯(cuò)的