亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

老師布置的課后習題,我不按規定的輸入整型數字而是輸入字符的時候程序陷入死循環怎么解決

主類:

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);

}


}


正在回答

2 回答

Scanner in = new Scanner(System.in);這句代碼應該放在while循環內,因為你放在外面的話每次都會直接使用上次輸入的字符串值,放進去的話會重新定義一個in,就不會出現死循環了。

1 回復 有任何疑惑可以回復我~
#1

淚在笑里哭 提問者

非常謝謝你的幫助,完美的幫我解決了問題。
2017-04-09 回復 有任何疑惑可以回復我~

試了下你的代碼確實存在這個問題。想了想應該和c中輸入緩沖區不能正常清除的問題是一樣的。

大概原因是當Scanner讀入了字符的時候,輸入緩沖區中讀到的字符沒有清除,因此之后的每一次while循環就會默

認的再次把之前輸入的值讀一遍,導致無限循環。

解決的辦法很直接,就是把緩沖區中的數據讀走(相當于清空),可以在你的第二個catch block中添加一行代碼

in.nextLine();

這樣就可以了。

1 回復 有任何疑惑可以回復我~
#1

淚在笑里哭 提問者

同樣也非常謝謝你的回答,你的一樣也可以解決我代碼存在的問題,但限于我的水品,我覺得樓上的更加通俗易懂些
2017-04-09 回復 有任何疑惑可以回復我~
#2

慕粉0038445131 回復 淚在笑里哭 提問者

沒關系 問題解決了就好啦
2017-04-09 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

老師布置的課后習題,我不按規定的輸入整型數字而是輸入字符的時候程序陷入死循環怎么解決

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號