package Library;
public class Book {
public String name;
public int id;
public Book(String name, int id) {
this.id = id;
this.name = name;
}
}
package Library;
import java.util.InputMismatchException;
import java.util.Scanner;//导入Scanner工具
public class Library {
public static void main(String[] args) {
Book[] books = {new Book("论语",1), new Book("高数",2),
new Book("电路",3), new Book("大英",4)};
System.out.println("输入命令:1-按名称查书;2-按序号查书");
int checkWay = 0;
while(true) {
checkWay = inputCheck();
if(checkWay!=1 && checkWay!=2)
System.out.println("命令错误,请重新输入!");
else break;
}
while(true) {
boolean bookExist = false;
while(bookExist == false) {
if(checkWay == 1) {
System.out.print("请输入图书名称:");
Scanner scan = new Scanner(System.in);
String name = scan.next();
for(Book book : books) {
if(name.equals(book.name)) {
System.out.println("找到图书:"+book.name+" 序号为:"+book.id);
bookExist = true;
}
}
if(bookExist == false)
System.out.println("您要的图书不存在!");
}
else if(checkWay == 2) {
System.out.print("请输入图书序号:");
int id = inputCheck();
for(Book book : books) {
if(id == book.id) {
System.out.println("找到图书:"+book.name+" 序号为:"+book.id);
bookExist = true;
}
}
if(bookExist == false)
System.out.println("您要的图书不存在!");
}
}
System.out.println("请问是否继续查书?1-是 2-否");
int continueOrNot = 0;
while(true) {
continueOrNot = inputCheck();
if(continueOrNot!=1 && continueOrNot!=2)
System.out.println("命令错误,请重新输入!");
else break;
}
if(continueOrNot == 2) {
System.out.println("感谢您的使用,再见!");
break;
}
}
}
public static int inputCheck() { //循环获取输入直至检测到数字
Scanner scan = new Scanner(System.in);
while(true) {
try{
int input = scan.nextInt();
return input; //若上一行代码未报错则返回输入值
}catch(InputMismatchException e) {
System.out.println("请根据提示输入数字命令!");
scan.next(); //读取输入内容防止影响下次循环
}
}
}
}
点击查看更多内容
2人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦