自定异常NameException 图书名称异常
package com.book;
public class NameException extends Exception {
public NameException() {
}
public NameException(String message) {
super(message);
}
}
自定异常NumException 图书序号异常
package com.book;
public class NumException extends Exception {
public NumException() {
}
public NumException(String message) {
super(message);
}
}
Book代码
package com.book;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Book {
static Scanner input = new Scanner(System.in);
static String[] bookname = new String[] { "论语", "C#", "JSP", "HTML", "JAVA" };
static boolean flag = true;
public static void main(String[] args) {
System.out.println("欢迎来到借书系统O~O");
System.out.println("图书列表:");
System.out.println("序号" + "\t" + "书名");
Book bk = new Book();
int i = 0;
for (String BK : bookname) {
System.out.println(i + 1 + "\t" + BK);
i++;
}
while (flag) {
try {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书!");
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String si = input.nextLine();
if (a == 1) {
try {
bk.ex1();
flag = false;
} catch (NameException e) {
System.out.println(e.getMessage());
}
} else if (a == 2) {
try {
bk.ex2();
flag = false;
} catch (Exception e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("序号输入错误!");
}
} catch (InputMismatchException e) {
System.out.println("命令输入错误!请根据提示输入数字命令!");
}
}
}
public void ex1() throws NameException {
System.out.println("输入图书名称:");
String b = Book.input.next();
boolean p = false;
for (String bb : bookname) {
if (b.equals(bb)) {
p = true;
}
}
if (p) {
System.out.println("book:" + b);
} else {
throw new NameException("图书不存在!");
}
}
public void ex2() throws NumException {
System.out.println("输入图书序号:");
int c = Book.input.nextInt();
if (c >= 1 && c <= bookname.length) {
System.out.println("book:" + bookname[c - 1]);
} else {
throw new NumException("图书不存在!");
}
}
}
写了一晚上。。不容易啊 小白入门努力学习中 希望大佬们多给意见 如何优化
点击查看更多内容
2人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦