第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

老師布置的課后習(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);

}


}


正在回答

2 回答

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

1 回復(fù) 有任何疑惑可以回復(fù)我~
#1

淚在笑里哭 提問者

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

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

大概原因是當(dāng)Scanner讀入了字符的時候,輸入緩沖區(qū)中讀到的字符沒有清除,因此之后的每一次while循環(huán)就會默

認(rèn)的再次把之前輸入的值讀一遍,導(dǎo)致無限循環(huán)。

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

in.nextLine();

這樣就可以了。

1 回復(fù) 有任何疑惑可以回復(fù)我~
#1

淚在笑里哭 提問者

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

慕粉0038445131 回復(fù) 淚在笑里哭 提問者

沒關(guān)系 問題解決了就好啦
2017-04-09 回復(fù) 有任何疑惑可以回復(fù)我~

舉報

0/150
提交
取消

老師布置的課后習(xí)題,我不按規(guī)定的輸入整型數(shù)字而是輸入字符的時候程序陷入死循環(huán)怎么解決

我要回答 關(guān)注問題
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號