图书
public class B {
private String name;
private int num;
public B(String n,int nu){
this.name = n;
this.num = nu;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
自定义异常
public class EnException extends Exception{
public EnException(){
}
public EnException(String massage){
super(massage);
}
}
运行
import java.util.Scanner;
public class Book {
public static void main(String[] args) {
// TODO Auto-generated method stub
B book[] = {new B("程序设计基础",1),new B("高数",2),new B("数据结构",3)};
while(true){
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
Scanner in = new Scanner(System.in);
try{
int n = in.nextInt();
if(n==1){
System.out.println("输入图书名称:");
String name = in.next();
boolean f=false;
for(int i = 0; i < book.length; i++){
if(name.equals(book[i].getName())){
f = true;
System.out.println("book:"+ book[i].getName());
}
}if(!f){
warn();
}
}
else if(n==2){
System.out.println("输入图书序号:");
int num = in.nextInt();
boolean f=false;
for(int i=0;i<book.length;i++)
if(num==book[i].getNum())
{
System.out.println("book:"+book[i].getName());
f=true;
}
if(!f){
warn();
}
}
else {
System.out.println("命令输入错误!请根据提示输入数字命令!");
}
}catch(EnException e){
System.out.println("图书不存在!");
}catch(Exception e){
System.out.println("命令输入错误!请根据提示输入数字命令!");
}
}
}
public static void warn()throws EnException{
throw new EnException("图书不存在!");
}
}