/*
* 定义个字符串数组,保存图书信息
*
*/
import java.util.Scanner;
public class BookManeger {
public static void main(String[] args) {
String[] books = {"C语言","计算机网络","Java数据库高级教程","编程之美","英语四六级"};
BookManeger myBook = new BookManeger();
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("输入命令:1-输入图书名称查询,2-输入图书序号查询");
int m = inputNum();
try{
switch(m){
case 1:
System.out.println("请输入图书名称:");
String str = (new Scanner(System.in)).next();
myBook.findBooks(str, books);
break;
case 2:
System.out.println("请输入图书序号:");
int num = (new Scanner(System.in)).nextInt();
myBook.findBooksName(num, books);
break;
default:
System.out.println("输入命令错误:");
continue;
}
break;
}catch(Exception e){
System.out.println(e.getMessage());
continue;
}
}
}
//输入图书名称进行查询
public void findBooks(String input,String books[]) throws Exception
{
for ( int i=0; i<books.length; i++){
if ( input.equals(books[i]) ){
System.out.println("图书名称为:"+books[i]);
return;
}
}
throw new Exception("哈哈,您输入的书本不存在!!");
}
//输入图书序号查询
public void findBooksName(int input,String books[]) throws Exception
{
if ( input<books.length && input >=0){
System.out.println("对应的图书为:"+books[input]);
}
else{
throw new Exception("请输入正确的图书序号,不存在此序号的图书");
}
}
public static int inputNum()
{
try {
int k = new Scanner(System.in).nextInt();
return k;
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("请按照提示,输入正确的指令");
int k = new Scanner(System.in).nextInt();
return k;
}
}
}
public static int inputNum(){
while(true){
try {
int k = new Scanner(System.in).nextInt();
return k;
} catch (Exception e) {
System.out.println("请按照提示,输入正确的指令");
}continue;
}
}
最后这个修正输入格式这个方法,只能操作两次,假如两次都输入不符合int的字符,则该系统结束
因此用while循环 不断的进入try块,知道输入符合Int的为止
你的那个findBooksName里面return 是跳出循环吗?还有那个switch语句外面那个break要了没用啊