import java.util.Scanner;
public class Demo {
private static Scanner go = new Scanner(System.in);
//数组定义
static String[] books = {"西语言","西家家","数据裤"};
public static void main(String[] args){
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
Scanner in =new Scanner(System.in);
String book;
try {
int num = in.nextInt();
if(num == 1) {
//判断用户想要使用名称查找图书
book = getBookByName(books);
//获取用户的图书
System.out.println("book:"+book);
}else if(num == 2) {
//判断用户想要用序号来查找图书
book = getBookByNumber(books);
//获取图书
System.out.println("book:"+book);
}
//只要输入的不是1或2,程序结束
else {
System.out.println("输入不对,请重新运行!谢谢!");
}
//如果不是整型那么程序也结束,重新运行
}catch(Exception e) {
System.out.println("命令输入错误!请根据提示输入数字命令!请重新运行!谢谢!");
}
}
//匹配名称输入,返回图书名称
public static String getBookByName(String[] book) throws Exception{
System.out.println("输入图书名称:");
String bookname = go.next();
for(int i = 0;i <= books.length;i++) {
if(bookname.equals(books[i])){
return books[i];
}
}
throw new Exception("图书不存在!请重新运行!谢谢!");
}
//匹配序号输入返回图书名称
public static String getBookByNumber(String[] book) throws Exception{
System.out.println("输入图书序号:");
try {
//直接输出,如果下标越界则会报错
int booknumber = go.nextInt();
String book1 = books[booknumber-1];
return book1;
}catch(Exception e){
Exception ok = new Exception("图书不存在2!请重新运行!谢谢!");
throw ok;
}
}
}
代码结构很清晰,赞
package weak2;
import java.util.Scanner;
public class Demo {
private static Scanner go = new Scanner(System.in);
//数组定义
static String[] books = {"西语言","西家家","数据裤"};
public static void main(String[] args){
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
Scanner in =new Scanner(System.in);
String book;
try {
int num = in.nextInt();
if(num == 1) {
//判断用户想要使用名称查找图书
book = getBookByName(books);
//获取用户的图书
System.out.println("book:"+book);
}else if(num == 2) {
//判断用户想要用序号来查找图书
book = getBookByNumber(books);
//获取图书
System.out.println("book:"+book);
}
//只要输入的不是1或2,程序结束
else {
System.out.println("输入不对,请重新运行!谢谢!");
}
//如果不是整型那么程序也结束,重新运行
}catch(Exception e) {
System.out.println("命令输入错误!请根据提示输入数字命令!请重新运行!谢谢!");
}
}
//匹配名称输入,返回图书名称
public static String getBookByName(String[] book) throws Exception{
System.out.println("输入图书名称:");
String bookname = go.next();
for(int i = 0;i <= books.length;i++) {
if(bookname.equals(books[i])){
return books[i];
}
}
throw new Exception("图书不存在!请重新运行!谢谢!");
}
//匹配序号输入返回图书名称
public static String getBookByNumber(String[] book) throws Exception{
System.out.println("输入图书序号:");
try {
//直接输出,如果下标越界则会报错
int booknumber = go.nextInt();
String book1 = books[booknumber-1];
return book1;
}catch(Exception e){
Exception ok = new Exception("图书不存在2!请重新运行!谢谢!");
throw ok;
}
}
}