问答详情
源自:1-9 经验总结

请大神帮忙看一下,为什么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);

}

}

}

}


提问者:慕粉4022211 2016-10-05 20:53

个回答

  • 慕粉4022211
    2016-10-06 16:56:03

    经过楼主自己进一步学习研究发现break放错地方了,应该放在

    else{

    throw new Exception();

    }

    break;//退出程序,break放在这里,跳出整个while循环,退出程序


  • worth丶
    2016-10-05 21:01:00

    break只能用在循环中,用在if语句中当然没用