供大家参考
package com.class3;
public class FindBook {
public int id;
public String name;
public FindBook(int id,String name) {
// TODO Auto-generated constructor stub
this.id=id;
this.name=name;
}
public String GetBook() {
// TODO Auto-generated constructor stub
return this.id+"\t"+this.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;
}
}
package com.class3;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InitialBook {
FindBook fb[]= {new FindBook(1,"论语"),new FindBook(2,"数学")};
public static void main(String[] args) {
InitialBook in=new InitialBook();
in.menu1();
}
public void menu1() {
System.out.println("欢迎使用图书查询小程序,书籍清单如下:");
System.out.println("图书序号\t书名");
for(int i=0;i<fb.length;i++) {
System.out.println(fb[i].GetBook());
}
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
Scanner sc=new Scanner(System.in);
int input=sc.nextInt();
switch(input) {
case 1: menu2();
break;
case 2: menu3();
break;
default:break;
}
sc.close();
}
public void menu2() {
Scanner sc=new Scanner(System.in);
System.out.println("请输入书名查找:");
String input=sc.nextLine();
boolean flag=false;
for(int i=0;i<fb.length;i++) {
if(input.equals(fb[i].getName())) {
System.out.println("根据名称搜索书名为:"+fb[i].getName());
flag=true;
break;
}
}
if(flag==false) {
System.out.println("书名不存在,请重新输入");
menu2();
}
sc.close();
}
public void menu3() {
try {
Scanner sc=new Scanner(System.in);
System.out.println("请输入图书序号查找:");
int input=sc.nextInt();
boolean flag=false;
for(int j=0;j<fb.length;j++) {
if(input==fb[j].getId()) {
System.out.println("根据序号搜索书名为:"+fb[j].getName());
flag=true;
break;
}
}
if(flag==false) {
System.out.println("书名不存在,请重新输入");
menu3();
}
sc.close();
}catch(InputMismatchException e) {
System.out.println("命令输入错误!请根据提示输入数字命令");
menu3();
}
}
}