一个优雅的男孩
2020-02-26 23:15
import java.util.Scanner;
public class Initial {
String [] BookList=new String[] {"高数","Java","数据结构","C++","计算机网络"};
public static void main(String[] args) {
Initial init=new Initial();
init.start();
}
public void start() {
int a=1;
ChooseMethod();
}
public void ChooseMethod() {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
Scanner methodinput=new Scanner(System.in);
try {
int method=methodinput.nextInt();
if(method==1)
SearchByName();
if (method==2)
SearchByNumber();
} catch (NameException e) {
System.out.println(e.getMessage());
start();
}catch (NumberException e) {
System.out.println(e.getMessage());
start();
}catch (Exception e) {
System.out.println("命令输入错误!请按照提示输入数字命令!");
start();
}
}
public void SearchByNumber() throws NumberException{
System.out.println("输入图书序号:");
Scanner BookNumberInput=new Scanner(System.in);
int BookNumber = 0;
try {
BookNumber = BookNumberInput.nextInt();
} catch (Exception e) {
System.out.println("命令输入错误!请按照提示输入数字命令!");
SearchByNumber();
}
if(BookNumber<=BookList.length)
System.out.println("book:"+BookList[BookNumber-1]);
else
throw new NumberException();
}
public void SearchByName() throws NameException{
System.out.println("输入图书名称:");
Scanner BooknameInput=new Scanner(System.in);
String Bookname=BooknameInput.nextLine();
Boolean check=false;
for(int i=0;i<BookList.length;i++) {
if(BookList[i].equals(Bookname))
{
System.out.println("book:"+Bookname);
check=true;
}
}
if(check==false)
throw new NameException();
}
}
public class NameException extends Exception{
NameException(){
super("图书不存在!");
}
}
public class NumberException extends Exception{
public NumberException() {
super("图书不存在!");
}
}
厉害,向你学习
Java入门第三季
409792 学习 · 4340 问题
相似问题