技术不高,可以参考
package com.exception.project;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class BookUtil {
//实例化一个List对象
List<Book> bookList = new ArrayList<Book>();
//查询方法
public void fun() {
BookUtil bu = new BookUtil();
System.out.println("输入命令:1-按名称查找图书;2-按序号查找图书");
// List<Book> list = new ArrayList<Book>();
//输出
Scanner scan = new Scanner(System.in);
try {
//输入一个数
int a = scan.nextInt();
boolean flag = false;
//判断是否为1 ,如果为1就进入按名称查找,如果为2就进入按序号查找 ,两者都不是就输出查询不到结果
if(a == 1) {
System.out.println("输入图书名称:");
String name = scan.next();
for (Book book : bookList) {
if(name.equals(book.getName())) {
System.out.println(book.toString());
flag = true;
break;
}
if(flag == false) {
System.out.println("图书名称:"+name+"没存在!");
fun();
}
}
}else if(a == 2) {
System.out.println("输入图书序号:");
int id = scan.nextInt();
for (Book book : bookList) {
if(id == book.getId()) {
System.out.println(book.toString());
flag = true;
break;
}
if(flag == false) {
System.out.println("图书名称:"+id+"没存在!");
fun();
}
}
}else {
System.out.println("输入数据不合格!");
fun();
}
}catch(Exception e) {
//设置异常提示信息
System.err.println("命令输入错误!请根据提示输入命令");
//如果出现异常就回调
fun();
}
}
//添加方法
public List<Book> addIdName() {
//创建一个book对象,并把book对象添加到list集合中
Book book1 = new Book(1,"高数");;
bookList.add(book1);
//创建一个book对象,并把book对象添加到list集合中
Book book2 = new Book(2,"java程序设计");
bookList.add(book2);
//创建一个book对象,并把book对象添加到list集合中
Book book3 = new Book(3,"数据库结构");
bookList.add(book3);
//创建一个book对象,并把book对象添加到list集合中
Book book4 = new Book(4,"软件工程");
bookList.add(book4);
//返回 list
return bookList;
}
}
package com.exception.project;
import java.util.Objects;
public class Book {
private int id;
private String name;
public Book() {
}
public Book(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Book : name=" + name + "";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return Objects.equals(name, book.name) &&
Objects.equals(id, book.id);
}
}
package com.exception.project;
import java.util.ArrayList;
import java.util.List;
public class test {
public static void main(String[] args) {
//实例化 BookUtil
BookUtil bu = new BookUtil();
bu.addIdName();
bu.fun();
}
}