請(qǐng)大神幫忙看一下,為什么else if里面使用break不能跳出while(true)循環(huán)
package java4;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Books {
//定義字符串?dāng)?shù)組用于保存圖書信息
//在static方法外部定義的屬性,要想在static類型的方法中調(diào)用,則要加上"static"
static String[] books={"高數(shù)","大學(xué)英語","數(shù)據(jù)結(jié)構(gòu)","JAVA入門","軟件工程","大學(xué)物理","數(shù)據(jù)庫"};
public static void main(String[] fargs) {
//創(chuàng)建Scannner對(duì)象用于用戶輸入
Scanner input=new Scanner(System.in);
//創(chuàng)建死循環(huán)while(true)用于保證系統(tǒng)運(yùn)行
stuu: while(true){
System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號(hào)查找圖書");
try {
//取得整型命令
int a=input.nextInt();
if(a==1){
System.out.println("輸入圖書名稱:");
//用戶輸入圖書名稱
String name=input.next();
//for循環(huán)遍歷所有圖書
for(int i=0;i<books.length;i++){
//books[i]==name;兩個(gè)引用之間可以用等于來進(jìn)行比較是否相等
if(books[i].equals(name)){
System.out.println("book: "+books[i]);
//跳出for循環(huán)
break;
}else if(i==books.length){
throw new RuntimeException("圖書不存在!");
}
}
}else if(a==2){
System.out.println("輸入圖書序號(hào):");
//用戶輸入圖書序號(hào)
int number=input.nextInt();
//輸出查找到的圖書信息
System.out.println("book:"+books[number]);
//跳出死循環(huán)
break;//有問題,break不能用在try--catch語句中!??!
}else{
throw new Exception();
}
}catch (InputMismatchException e) {
System.out.println("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示輸入數(shù)字命令!");
//進(jìn)行數(shù)據(jù)回滾
main(null);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("圖書不存在");
main(null);
}catch(RuntimeException e){
System.out.println(e.getMessage());
main(null);
}catch(Exception e){
System.out.println("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示輸入數(shù)字命令!");
main(null);
}
}
}
}
2016-10-06
經(jīng)過樓主自己進(jìn)一步學(xué)習(xí)研究發(fā)現(xiàn)break放錯(cuò)地方了,應(yīng)該放在
else{
throw new Exception();
}
break;//退出程序,break放在這里,跳出整個(gè)while循環(huán),退出程序
2016-10-05
break只能用在循環(huán)中,用在if語句中當(dāng)然沒用