海上钓鳌客
2015-07-26 22:02
package library; import java.util.Scanner; public class BorrowBook { public static void main(String[] args) { int choose; try{System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书"); @SuppressWarnings("resource") Scanner input = new Scanner(System.in); choose = input.nextInt(); if(choose!=1&&choose!=2) throw new Exception(); }catch(Exception e){ System.out.println("命令输入错误!请根据提示输入数字命令!"); System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书"); @SuppressWarnings("resource") Scanner input = new Scanner(System.in); choose = input.nextInt(); } if(choose==1){ System.out.println("请输入图书名称:"); @SuppressWarnings("resource") Scanner input = new Scanner(System.in); String bookName = input.nextLine(); NameFind find = new NameFind(); try { find.find(bookName); } catch(NameException e){ e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }//if(choose==1) if(choose==2){ System.out.println("请输入图书序号:"); @SuppressWarnings("resource") Scanner input2 = new Scanner(System.in); int bookNum = input2.nextInt(); NumFind find2 = new NumFind(); try { find2.find(bookNum); } catch (NameException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }//if(choose2) }//main }//class package library; public class NameFind { String[] name = {"高数","数据结构"}; public void find (String book)throws NameException { int count=0; for(int i=0;i<name.length;i++) if(book.equals(name[i])) System.out.println("book:"+name[i]); else count++; if(count==name.length&&(!name[count].equals(book))) throw new NameException("图书不存在"); }//find }//class package library; public class NumFind { String[] name = {"高数","数据结构"}; int[] num = {1,2}; int count = 0; public void find(int book)throws NameException{ for(int i=0;i<num.length;i++) if(book==num[i]){ System.out.println("book:"+name[i]); }else{ count++; } if(count==name.length&&(num[count]!=book)) throw new NameException("图书不存在"); } } package library; public class NameException extends Exception{ public NameException(){ System.out.println("图书不存在"); } public NameException(String msg){ super(msg); } }
异常的位置处理方式有错误,算法错误
这样的可以吗?可以我就把源代码给你。
我输出的有异常信息,不知道是不是你想要的
Java入门第三季
409788 学习 · 4340 问题
相似问题