老師布置的課后習(xí)題,我不按規(guī)定的輸入整型數(shù)字而是輸入字符的時候程序陷入死循環(huán)怎么解決
主類:
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("高數(shù)",1),new Book("JavaEE",2),new Book("Html5",3),
? ? ? ?new Book("數(shù)據(jù)結(jié)構(gòu)",4),new Book("C++",5),new Book("操作系統(tǒng)",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);這句代碼應(yīng)該放在while循環(huán)內(nèi),因為你放在外面的話每次都會直接使用上次輸入的字符串值,放進(jìn)去的話會重新定義一個in,就不會出現(xiàn)死循環(huán)了。
2017-04-08
試了下你的代碼確實存在這個問題。想了想應(yīng)該和c中輸入緩沖區(qū)不能正常清除的問題是一樣的。
大概原因是當(dāng)Scanner讀入了字符的時候,輸入緩沖區(qū)中讀到的字符沒有清除,因此之后的每一次while循環(huán)就會默
認(rèn)的再次把之前輸入的值讀一遍,導(dǎo)致無限循環(huán)。
解決的辦法很直接,就是把緩沖區(qū)中的數(shù)據(jù)讀走(相當(dāng)于清空),可以在你的第二個catch block中添加一行代碼
這樣就可以了。