package com.jersey;
import java.util.*;
import javax.sql.rowset.spi.SyncFactoryException;
public class LibSystem {
static Book[] books={new Book("论语","000001"),new Book("老子","000002"),new Book("java编程思想","000003")};
public static void main(String[] args){
System.out.println("欢迎来到iLibrary图书检索系统!");
Scanner input=new Scanner(System.in);
System.out.println("请选择:1.按书名检索 2.按编号检索 3.退出系统");
int n=input.nextInt();
switch(n){
case 1:
System.out.println("请输入您所要检索的图书名称");
String a=input.next();
try{
String result=SearchByName(a);
System.out.println("您所选的《"+result+"》已找到");
}catch(Exception e){
e.printStackTrace();
System.out.println("您检索的图书不存在!");
}
break;
case 2:
System.out.println("请输入您所要检索的图书编码");
String b=input.next();
try{
String result2=SearchByCode(b);
System.out.println("您所选的《"+result2+"》已找到");
}catch(Exception e){
e.printStackTrace();
System.out.println("您输入的编码有误,请重新输入!");
}
break;
case 3:
System.exit(0);
default:
System.out.println("您的输入有误!请重新输入!");
}
}
public static String SearchByName(String a) throws Exception{
for(int i=0;i<books.length;i++){
if(a.equals(books[i].name)){
continue;
}
else{
throw new Exception();
}
}
return a;
}
public static String SearchByCode(String b) throws Exception{
String s2=b;
for(int i=0;i<books.length;i++){
if(b.equals(books[i].code)){
s2=books[i].name;
break;
}
else{
throw new Exception();
}
}
return s2;
}
}诸位还有什么改进的建议也请告诉我,谢谢!
public static void main(String[] args) {
service();
}
public static void service(){
System.out.println("欢迎来到iLibrary图书检索系统!");
Scanner input = new Scanner(System.in);
System.out.println("请选择:1.按书名检索 2.按编号检索 3.退出系统");
int n = input.nextInt();
switch (n) {
case 1:
System.out.println("请输入您所要检索的图书名称");
String a = input.next();
try {
String result = SearchByName(a);
System.out.println("您所选的《" + result + "》已找到");
} catch (Exception e) {
e.printStackTrace();
System.out.println("您检索的图书不存在!");
}
service();
break;
case 2:
System.out.println("请输入您所要检索的图书编码");
String b = input.next();
try {
String result2 = SearchByCode(b);
System.out.println("您所选的《" + result2 + "》已找到");
} catch (Exception e) {
e.printStackTrace();
System.out.println("您输入的编码有误,请重新输入!");
}
service();
break;
case 3:
System.out.println("结束!");
break;
default:
System.out.println("您的输入有误!请重新输入!");
service();
}
}
public static String SearchByName(String a) throws Exception {
return "by name";
}
public static String SearchByCode(String b) throws Exception {
return "by code";
}我这没有Book类,模拟一下吧
示例代码中的异常处理也有问题啊,压根不能判断输入的信息是否与已有数据相匹配,而且真心不明白这里的两个异常处理有什么作用!
也可以尝试一下
boolean retry=true;
while(needretry){
try{
//执行的代码块1
retry=false;//没有错误不需要重来
}catch(Exception e){
//执行代码块2
retry=true;//有错误,要重来
}
}
这个模板只是大概的,你可以根据需要添加其他条件语句及判断。
亲测有效