以下代码可以正常运行 比较不明白的是 因为按字符串查找图书所以定义了String型保存A 如果输入INT型数据则不会报错 此处可如何解决 也希望收到其他可以指正的地方 package com.ExceptionEXE; import java.util.Scanner; public class ExceptionEXE { String books[]={"0位置为空","Chinese","English","Math"}; public static void main(String[] args) throws NoBooksException { ExceptionEXE e = new ExceptionEXE(); System.out.println("输入1,按书名查询;输入2,按序号查询:"); Scanner D = new Scanner(System.in); int input = D.nextInt(); switch(input){ case 1: try { e.searchName(); } catch (NoBooksException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } break; case 2: try { e.searchNumber(); } catch (NoNumException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } break; default: System.out.println("输入错误,输入值只能为1或2"); break; } D.close(); } public void searchName() throws NoBooksException{ System.out.println("按照字符串查找:"); Scanner a = new Scanner(System.in); String A = a.next(); int count = 0; for(int i=0;i<books.length;i++){ if(A.equals(books[i])){ // System.out.println("相等"); System.out.println(i+" "+books[i]); } count++; if(count>books.length){ throw new NoBooksException("没有图书"); } } } public void searchNumber()throws NoNumException{ Scanner a = new Scanner(System.in); System.out.println("按照数字查找:"); int B = a.nextInt(); if(B<1||B>3){ throw new NoNumException("数字超出范围"); } System.out.println(B+" "+books[B]); } }
package com.ExceptionEXE; public class NoBooksException extends Exception{ public NoBooksException(String msg){ super(msg); } }
package com.ExceptionEXE; public class NoNumException extends Exception{ public NoNumException(String msg){ super(msg); } }
A未来战士N
相关分类