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