package com.study2;
import java.util.Scanner;
//异常处理
//所有异常类都继承于Throwable
//两大类,Exception类和Error类
//Error: VirtualMachineError,ThreadDeath,虚拟机错误,线程锁死
//Exception:非检查异常RuntimeException(运行时异常)
//检查异常:IOException,SQLException
////RuntimeException:
//空指针异常(NullPointerException),数组越界异常(ArrayIndexOutOfBoundsException)
//类型转换异常(ClassCastException),算术异常(ArithmeticException)
//InputMismatchException输入不匹配异常
//ArithmeticException算术异常
//Exception类中的printStackTrace();堆栈跟踪信息
//InitCause方法,追溯异常的原因,对异常进行包装
//自定义异常
//nextLine可以读到空格,next不行,两者遇见回车结束
public class Initail {
public static void main(String[] args) {
choose();
}
//书架
private static Scanner input = new Scanner(System.in);
private static Book[] books = new Book[]{
new Book("龙族", "001"),
new Book("三体", "002"),
new Book("毛选", "003"),
};
//选书
private static void choose() {
System.out.println("输入命令:1 按照书名查找图书 2 按照ISBN号查找图书");
try {
int choice = input.nextInt();
if (choice == 1) SearchByName();
if (choice == 2) SearchByNumber();
else{
System.out.println("输入错误,请重新输入");
choose();
}
} catch (NameException e) {
e.printStackTrace();
choose();
}catch (NumberException e){
e.printStackTrace();
choose();
}catch (Exception e){
System.out.println("输入命令有误");
choose();
}
}
//按照书名选书
private static void SearchByName() throws NameException {//抛出声明
System.out.println("输入要查找的书籍名称:");
String inputname="0";
try {
inputname = input.next();
} catch (Exception e) {//异常时的处理
System.out.println("输入不合法");
SearchByName();//重新进入该方法
}
boolean check = false;
//检查输入是否合法
//equals函数:字符串比较,若相等则返回true,否则返回false
for (int i = 0; i < books.length; i++) {
if (books[i].getBookname().equals(inputname)) {
System.out.println("书籍名称:" + inputname + " " + "ISBN:" + books[i].getISBN());
check = true;
}
}
if (check == false) throw new NameException();
}
//按照IBSN号选书
private static void SearchByNumber() throws NumberException {//抛出声明
String inputnumber ="0";
System.out.println("输入要查找的书籍ISBN:");
try {
inputnumber = input.next();
} catch (Exception e) {//异常时的处理
System.out.println("输入不合法");
SearchByNumber();
}
boolean check = false;
//检查输入是否合法
for (int i = 0; i < books.length; i++) {
if (books[i].getISBN().equals(inputnumber)) {
System.out.println("书籍名称:" + books[i].getBookname() + " " + "ISBN:" + inputnumber);
check = true;
}
}
if (check == false) throw new NumberException();
}
}
//自定义异常
package com.study2;
public class NameException extends Exception {
//构造方法
NameException(){
super("该图书不存在!");
}
}
package com.study2;
public class NumberException extends Exception {
NumberException(){
super("该图书不存在!");
}
}
package com.study2;
public class Book {
private String bookname;
private String ISBN;// International Standard Book Number
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
//有参的构造函数
public Book(String bookname,String ISBN){
this.bookname=bookname;
this.ISBN=ISBN;
}
}