0.目标
1.程序
有点小问题,但是属于输入角度的问题(思想已经到位了);
package com.yh.rentbook;
import java.util.InputMismatchException;
import java.util.Scanner;
public class RentBookMain {
public static void main(String[]args){
String[]books = new String[]{"高数","Java","C","线性代数","中国式管理"};
Scanner input = new Scanner(System.in);
boolean inputSearchWayWrong = true;
while(inputSearchWayWrong) {//如果一直输入错误则一直要求输入
try {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
int searchByInt = 0;
searchByInt = input.nextInt();//获取输入命令
inputSearchWayWrong = false;
if(searchByInt==1){//按名称查询
String name="";
System.out.println("输入需要查询的书名:");
name = input.nextLine();
String result = searchBookByName(books,name);
System.out.println("book:"+result);
}else if(searchByInt==2){//按序号查询
int number = 0;
boolean numberInvalid = true;
while(numberInvalid) {
try{
System.out.println("输入需要查询的序号:");
number = input.nextInt();
numberInvalid = false;
}catch(NumberFormatException|InputMismatchException e){
System.out.println("命令输入错误!请根据提示输入数字命令!");
numberInvalid = true;
}
String result = searchBookByNumber(books, number);
System.out.println("book:" + result);
}
}
} catch(MyBookNameNotExistsException|MyBookNumberNotExistsException e1){
System.out.println("图书不存在!?");
} catch(NumberFormatException|InputMismatchException e2) {
System.out.println("命令输入错误!请根据提示输入数字命令!!");
inputSearchWayWrong = true;
}
}
}
//根据书名查找图书
public static String searchBookByName(String[]books,String name) throws MyBookNameNotExistsException{
for(int i=0;i<books.length;i++){
if(name.equals(books[i])) {
System.out.println("找到了!");
return name;
}
}
throw new MyBookNameNotExistsException("图书不存在!");
}
//根据序号查找图书
public static String searchBookByNumber(String[]books,int number) throws MyBookNumberNotExistsException{
if(number>=1&&number<=books.length){
return books[number-1];
}
throw new MyBookNumberNotExistsException("图书不存在!");
}
}
class MyNumberFormatException extends RuntimeException{
public MyNumberFormatException(String message){
super(message);
}
}
class MyBookNameNotExistsException extends RuntimeException{
public MyBookNameNotExistsException(String message){
super(message);
}
}
class MyBookNumberNotExistsException extends RuntimeException{
public MyBookNumberNotExistsException(String message){
super(message);
}
}
<后面再改吧!>
解决的时候参考这个(Mark一下):
https://blog.csdn.net/zhaoyy0513/article/details/79231877?utm_source=blogxgwz1