老師布置的課后習題,我不按規定的輸入整型數字而是輸入字符的時候程序陷入死循環怎么解決
主類:
package com.imooc.borrowBook;
import java.util.Scanner;
public class BookManager {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Book books[] = {new Book("高數",1),new Book("JavaEE",2),new Book("Html5",3),
? ? ? ?new Book("數據結構",4),new Book("C++",5),new Book("操作系統",6)};
while(true){
System.out.println("請選擇查找方式:");
System.out.println("1.按書名查找圖書 ? ? 2.按序號查找圖書 ? ?3.退出");
try{
int num = in.nextInt();
if(num==1){
System.out.println("請輸入書名:");
String num_1 = in.next();
//boolean name = false;
for(int i=0;i<books.length;i++){
if(num_1.equals(books[i].bookName)){
System.out.println("book:"+books[i].bookName);
//name = true;
}else
throw new NoExistException();
}
}else if(num==2){
System.out.println("請輸入書的序號:");
int num_2 = in.nextInt();
//boolean number = false;
for(int i=0;i<books.length;i++){
if(num_2 == books[i].bookNum){
System.out.println("book:"+books[i].bookName);
//number = true;
}else if (num_2>books.length||num_2<=0){
throw new NoExistException();
}
}
}else if(num==3){
System.out.println("歡迎下次再來!");
System.exit(0);
}else?
throw new Exception();
//System.out.println("命令輸入錯誤,請按提示輸入?。?!");
}
catch(NoExistException e){
//e.printStackTrace();
System.out.println("該圖書不存在!");
System.out.println();
}catch(Exception e){
//e.printStackTrace();
System.out.println("命令輸入錯誤,請按提示輸入?。?!");
System.out.println();
}
}
}
}
書類:
package com.imooc.borrowBook;
public class Book {
public String bookName;
public int bookNum;
public Book(String bookName,int bookNum){
this.bookName = bookName;
this.bookNum = bookNum;
}
}
自定義異常類:
package com.imooc.borrowBook;
public class NoExistException extends Exception {
public NoExistException(){
}
public NoExistException(String message){
super(message);
}
}
2017-04-08
Scanner in = new Scanner(System.in);這句代碼應該放在while循環內,因為你放在外面的話每次都會直接使用上次輸入的字符串值,放進去的話會重新定義一個in,就不會出現死循環了。
2017-04-08
試了下你的代碼確實存在這個問題。想了想應該和c中輸入緩沖區不能正常清除的問題是一樣的。
大概原因是當Scanner讀入了字符的時候,輸入緩沖區中讀到的字符沒有清除,因此之后的每一次while循環就會默
認的再次把之前輸入的值讀一遍,導致無限循環。
解決的辦法很直接,就是把緩沖區中的數據讀走(相當于清空),可以在你的第二個catch block中添加一行代碼
這樣就可以了。