求教下大神 我如果不把 Scanner input = new Scanner(System.in);在每個方法中都重新定義一下,為什么在異常時候不會讓我重新輸入,就會陷入無盡循環(huán)。
package com.Project3;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public void findBook(){
for(int i = 1;;){
try{
System.out.println("輸入命令:1-按照書名查書;2-按照序號查書");
Scanner input = new Scanner(System.in);
int k = input.nextInt();
String name;
if(k == 1){
name = getbookname();
System.out.println("book:"+name);
break;
}
if(k==2){
name = getbooknum();
System.out.println("book:"+name);
break;
}
else {
System.out.println("輸入有誤");
continue;
}
}catch(InputMismatchException e){
System.out.println("命令輸入錯誤!請根據(jù)指令輸入數(shù)字命令!");
}
catch(Exception e){
System.out.println(e.getMessage());
}
continue;
}
}
public String getbookname() throws Exception{
Scanner in = new Scanner(System.in);
System.out.println("請輸入圖書名稱:");
String name = in.next();
if(name.equals("高數(shù)")){
return name;
}else{
throw new Exception("圖書不存在!");
}
}
public String getbooknum() throws Exception{
while(true){
System.out.println("請輸入圖書序號:");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
try{
if(num == 1){
return "數(shù)據(jù)結(jié)構(gòu)";
}else{
throw new Exception("圖書不存在");
}
}catch(InputMismatchException e){
throw new Exception("命令輸入錯誤!請根據(jù)指令輸入數(shù)字命令");
}
}
}
public static void main(String[] args) {
Test c = new Test();
c.findBook();
}
}
2017-05-16
我的意思是把Scanner放在外部,然后每個方法輸入時候都調(diào)用,如果普通循環(huán)都會返回讓重新輸入,但是有拋出異常的循環(huán),拋出異常后就陷入無盡循環(huán)了,不會再讓你輸入信息了。
2017-05-14
因為在方法體中定義的只在該方法體中有效啊