不知道怎么去處理循環
package?library;
import?java.util.InputMismatchException;
import?java.util.Scanner;
public?class?tushu?{
?public?static?String[]?books?=?{?"高數",?"代數",?"英語",?"語文"?};
?public?static?String?byBookName(String?filterName)?{
??for?(String?book?:?books)?{
???if?(book.contains(filterName))?{
????return?book;
???}
??}
??return?"不存在";
?}
?public?static?String?byBookID(int?bookID)?{
??return?books[bookID?-?1];
?}
?public?static?void?main(String[]?args)?{
??System.out.println("輸入命令:?1-按照名稱查找圖書;?2-按照序號查找圖書");
??Scanner?scanner?=?new?Scanner(System.in);
??//?當輸入的值為非1和非2的時候,?提示重新輸入!
??int?filterType?=?0;
??int?i?=?0;
??do?{
???if?(i?!=?0)?{
????System.out.println("命令輸入錯誤!?請根據提示輸入數字命令!");
???}
???i++;
???try?{
????filterType?=?scanner.nextInt();
???}?catch?(InputMismatchException?e)?{
????scanner?=?new?Scanner(System.in);
???}
??}?while?(filterType?!=?1?&&?filterType?!=?2);
??
??//進入查找圖書的流程
??if?(filterType?==?1)?{
???System.out.println("輸入圖書名稱:");
???String?bookName?=?byBookName(scanner.next());
???if?(bookName.equals("不存在"))?{
????System.out.println("圖書不存在!");
???}?else?{
????System.out.println("book:"?+?bookName);
???}
??}?else?{
???System.out.println("輸入圖書序號:");
???try?{
????String?bookName?=?byBookID(scanner.nextInt());
????System.out.println("book:"?+?bookName);
???}?catch?(InputMismatchException?e)?{
????System.out.println("輸入類型錯誤,?拋出錯誤命令異常,?提示重新輸入");
???}?catch?(ArrayIndexOutOfBoundsException?e)?{
????System.out.println("圖書不存在!");
???}
???scanner.close();
??}
?}
}
?老師的代碼
while?(true)?{
???System.out.println("輸入圖書序號:");
???try?{
????//獲取輸入的圖書序號(數組下標)
????int?index?=?inputCommand();
????//若返回值為-1
????if(index?==?-1){
?????System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");
?????continue;
????}
????//若不出現”數組下標越界異常“,則返回相應位置的圖書
????String?book?=?books[index];
????return?book;
???}?catch?(ArrayIndexOutOfBoundsException?e)?{
????//輸入的序號不存在(引發”數組下標越界異常“),則拋出”圖書不存在異常“
????Exception?bookNotExists?=?new?Exception("圖書不存在!");
????bookNotExists.initCause(e);
????throw?bookNotExists;
???}
??}
2015-08-04
你可以在異常處理里重新定義輸入類對象,就可以避免死循環了
2015-08-03
進入死循環的原因是因為你的數據緩存區中依舊保存著你輸入的字母,而此時調用nextInt方法會自動解析數據緩存區所保留的字母,類似c里面用fflush(stdin)可清除~不知道java中有沒有類似功能的這個