创建一个bookname类
package booksyst;
public class bookname
{
public String name;
public int num;
//定义个bookname的构造函数
public bookname(String name,int num)
{
this.name = name;
this.num = num;
}创建book主程序
package booksyst;
import java.util.Scanner;
public class book {
// 定义变量
static int chose1;
static String name;
static int bookid;
// 定义bookname 类数组
bookname[] book1 = { new bookname("物理", 1), new bookname("语文", 2), new bookname("数学", 3) };
/** * @param args * @throws Exception */
public static void main(String[] args) throws Exception
{
// TODO Auto-generated method stub
// 定义全局变量
book text1 = new book();
text1.run();
}
public void run() throws Exception
{
// 选择查询方式
chose();
// 输入图书名称
if (chose1 == 1)
{
finename();
}
// 输入图书序号
if (chose1 == 2) {
fineid();
} }
private void fineid() throws Exception {
// TODO Auto-generated method stub
try {
System.out.println("请输入图书的序号");
Scanner input = new Scanner(System.in);
bookid = input.nextInt();
for (bookname bookname : book1) {
if (bookname.num == bookid) {
System.out.println("图书馆里找到了您的图书信息:" + bookname.name +
",ID:" + bookname.num);
return;
} }
throw new Exception();
}
catch (Exception e)
{
System.out.println("查找的图书不存在!");
run();
// 如果有异常信息抛出,重新调用run方法
} }
private void finename() throws Exception {
// TODO Auto-generated method stub
try {
System.out.println("请输入图书的名称");
Scanner input = new Scanner(System.in);
name = input.next();
for (bookname bookname : book1) {
if (bookname.name.equals(name)) {
System.out.println("图书馆里找到了您的图书信息:" + bookname.name +",ID:" + bookname.num);
return;
} }
throw new Exception();
}
catch (Exception e)
{
System.out.println("查找的图书不存在!");
run(); // 如果有异常信息抛出,重新调用run方法
} }
private void chose() throws Exception {
// TODO Auto-generated method stub
try {
System.out.println("请输入选书命令:1-按名称查找 2-按序号查找");
Scanner input = new Scanner(System.in);
chose1 = input.nextInt();
if ((chose1 != 1) & (chose1 != 2)) {
throw new Exception();
} }
catch (Exception e) {
System.out.println("输入信息有误,请输入对应的数字序号");
run();
// 如果有异常信息抛出,重新调用run方法
} }}點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦