使用nextLine時(shí)什么時(shí)候無法接收輸入的行,注釋部分使用nextLine會(huì)出錯(cuò),而next就可以
import java.util.*;
public class findBook {
private String[] bookName={"高數(shù)","英語","C"};
private Scanner input = new Scanner(System.in);
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
findBook bk=new findBook();
while(true){
System.out.println("輸入命令:1-按照書名查找圖書,2-按照序號查找圖書");
try{
int num=bk.getCommond();
switch(num){
case 1:
bk.name();
break;
case 2:
bk.Number();
break;
case -1:
System.out.println("請輸入指定的數(shù)字");
break;
default:
System.out.println("輸入錯(cuò)誤?。。?);
break;
}
}catch(Exception e){
System.out.println("請重新輸入");
continue;
}
}
}
public int getCommond(){
int num;
try{
num=input.nextInt();
return num;
}catch(Exception e){
input.next();
return -1;
}
}
//按照書名查找
public void name() throws Exception{
String strname;
System.out.print("請輸入書名:");
//input.nextLine();
strname=input.nextLine(); ? ? //如果輸入用nextLine的話就無法接收到輸入???
for(int i=0;i<3;i++){
if(strname.equals(bookName[i])){
System.out.println("找到了"+strname);
return;
}
}
throw new Exception("圖書不存在!");
}
//按照序號查找
public void Number()throws Exception{
while(true){
System.out.println("請輸入書號:");
try{
int index=input.nextInt();
System.out.println("找到了"+bookName[index]);?
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("圖書不存在");
throw new Exception("BookNotExist");
}catch(Exception e){
System.out.println("輸入格式錯(cuò)誤,請根據(jù)提示輸入?。?!");
input.next();
continue;
}
}
}
}
2017-05-12
http://blog.csdn.net/wjy1090233191/article/details/42080029
這上面有詳細(xì)解釋
2017-05-12
問題同上!