我開始寫的時候也是遇到了困難,看了一個人的筆記後我有了思路,以下是我自己寫的代碼,但是運作的時候有點奇怪,輸入的字元必須在輸出那段話的下一行點選開始輸入,開始不再,是以輸入可能會出問題,有人知道為什麼開始輸入的地方不在第二行嗎?
public class nofoundexception extends Exception{
//定義自定義異常形參構造函數
public nofoundexception(String a){
//把形參傳遞給超類構造函數
super(a);
}
//定義無參構造函數
public nofoundexception(){
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class jieshuxitong {
//定義一個字元數組存放書本資訊
public static String[]bookname=new String[]{"武動乾坤","極品暧昧","鬥破蒼穹","神印王座","x龍時代","仙逆","龍族I火之晨曦","龍族II悼亡者之瞳","龍族III黑月之潮","龍族IV奧丁之淵"};
//定義一個布爾型常量并賦初始值
public static boolean flag=true;
//建立一個判斷并抛出自定義圖書不存在異常方法
public void test1(boolean flag) throws nofoundexception{
//根據判斷抛出異常
if(flag=true){
throw new nofoundexception("圖書不存在異常");
}
}
//根據書名查詢圖書類
public void checkbookname() throws nofoundexception{
//定義一個字元串數組存放輸入字元串
String name;
//定義break跳出的循環範圍
start:
//當抛出錯誤後循環輸出提示語句
while(true){
try{
//建立java輸入流
Scanner input=new Scanner(System.in);
System.out.println("請輸入書名:");
//儲存輸入資訊并付給一個字元串
name=input.nextLine();
for(int a=0;a
if(name.equals(bookname[a])){
//比對正确輸出書名并改變flag值,跳出while循環
System.out.println("book:"+name);
flag=false;
break start;
}
}
//判斷并抛出異常
test1(flag);
}catch(InputMismatchException e){
System.out.println("指令輸入錯誤!請根據提示輸入數字指令");
}catch(nofoundexception e){
System.out.println("圖書不存在");
}
}
}
//根據序号查詢圖書
public void checkbooknumber()throws nofoundexception{
int number;
//定義跳出循環範圍
start:
//當輸入錯誤時循環輸出
while(true){
try{
Scanner input1=new Scanner(System.in);
System.out.println("輸入圖書序号:");
number=input1.nextInt();
//判斷輸入數字是否超出數組長度
if(number>0&&number
System.out.println("book:"+bookname[number-1]);
//當找到圖書時改變flag值跳出循環
flag=false;
break start;
}else{
//根據flag值判斷并抛出異常
test1(flag);
}
}catch(InputMismatchException e){
System.out.println("指令輸入錯誤!請根據提示輸入數字指令");
}catch(nofoundexception e){
System.out.println("圖書不存在");
}
}
}
public static void main(String[]args){
start:
//根據flag的值判斷是否結束循環
while(flag){
try{
jieshuxitong s=new jieshuxitong();
int b=0;
Scanner input2=new Scanner(System.in);
System.out.println("輸入指令查找圖書:1-按書名,2-按序号");
b=input2.nextInt();
switch(b){
case 1:
s.checkbookname();
break start;
case 2:
s.checkbooknumber();
break start;
default:
System.out.println("指令輸入錯誤!請根據提示輸入數字指令");
}
}catch(InputMismatchException e){
System.out.println("指令輸入錯誤!請根據提示輸入數字指令");
}catch(nofoundexception e){
System.out.println("圖書不存在");
}
}
}
}