您的位置:首页 > 产品设计 > UI/UE

用while(true)和continue、break来实现在一个大循环里switch

2016-03-13 15:18 405 查看
while (true) {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
String book;
try {
//取得整型命令
int command = inputCommand();
//根据不同命令值,进行不同操作
switch (command) {
case 1://按照图书名称选择图书
book = getBookByName(books);
System.out.println("book:" + book);
break;
case 2://按照图书序号(数组下标)选择图书
book = getBookByNumber(books);
System.out.println("book:" + book);
break;
case -1://返回值为-1,说明输入有误
System.out.println("命令输入错误!请根据提示输入数字命令!");
continue;
default://其他值的命令均认为是错误命令
System.out.println("命令输入错误!");
continue;
}
break;//退出程序
} catch (Exception bne) {
//捕获”图书不存在异常“时,要求重新输入命令
System.out.println(bne.getMessage());
continue;
}
}


值得学习:

用while(true)和continue、break来实现在一个大循环里switch:

如果是选择了需要的“1”就break,如果是其他的(-1或者deafult)就用continue来反复循环,直到用户输入正确。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: