OnlyGirl
2015-03-06 19:17
********
自定义异常类:
package com.Bookrent;
public class ExtraException extends Exception{
}
********
Bookrent类:
package com.Bookrent;
public class Book {
private String bookName;
private int bookNum;
public Book(String bookName,int bookNum)
{
this.bookName = bookName;
this.bookNum = bookNum;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookNum() {
return bookNum;
}
public void setBookNum(int bookNum) {
this.bookNum = bookNum;
}
}
********
主函数:
package com.Bookrent;
import java.util.Scanner;
public class bookrent {
Book[] bookRent =
{new Book("高数",1),new Book("数据结构",2),new Book("操作系统",3),new Book("数据库",4)};
//将数组定义到全局范围方便其他函数使用;
public static void main(String[] args) {
// TODO Auto-generated method stub
bookrent br = new bookrent();
br.find();
}
public void find()
{
Scanner input = new Scanner(System.in);
System.out.println("输入命令:1.按照名称查找图书;2.按照序号查找图书");
int i = input.nextInt();
try
{
if(i == 1)
{
this.searchName();
}
else if(i == 2)
{
this.searchNum();
}
else
{
throw new Exception();
}
}catch(Exception e)
{
input = new Scanner(System.in);//对于输入有误的情况不会终止程序运行;
System.out.println("命令输入错误!请根据提示输入正确的命令!");
this.find();
}
}
public void searchName()//对于输入的信息进行判断并进行有效的处理(try catch)异常处理并循环
{
System.out.println("请输入要查询的书名:");
Scanner input = new Scanner(System.in);
String s = input.next();
try
{
for(Book br:bookRent)//遍历数组
{
if(br.getBookName().equals(s))//查看是否有何输入相同的书名
{
System.out.println("已找到图书");
System.out.println("图书:" + s);
this.find();//遍历后要及时退出否则会强制抛出异常;
}
else
{
throw new Exception();
}
}
}catch(Exception e)
{
System.out.println("查找的图书不存在");
this.find();
}
}
public void searchNum()
{
System.out.println("请输入要查询的书的序号:");
Scanner input = new Scanner(System.in);
try
{
int i = input.nextInt();
for(Book br:bookRent)
{
if(br.getBookNum() == i)
{
System.out.println("已找到图书");
System.out.println("图书:" + i);
this.find();
}
else
{
throw new ExtraException();//自定义异常的使用;对于多catch很有帮助;
}
}
}catch(ExtraException e)
{
System.out.println("查找的图书不存在");
this.find();
}catch(Exception e)
{
System.out.println("命令输入有误,请重新输入!");
this.searchNum();
}
}
}
可以,厉害
Java入门第三季
409792 学习 · 4340 问题
相似问题
回答 3
回答 2
回答 12
回答 2
回答 1