继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Java入门第三季——图书馆查书系统

Confused_wz
关注TA
已关注
手记 4
粉丝 13
获赞 44

运行效果1运行效果2

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(); //读取输入内容防止影响下次循环
			}
		} 
	}
}

打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP