交作业了!!!

来源:1-9 经验总结

慕雪8679015

2020-02-26 12:46

package exception_demo;

import java.util.Scanner;

public class Book {


public static void main(String[] args) {

// TODO Auto-generated method stub

Book bookObj = new Book();

bookObj.init();

}

public void init() {

String[] books = {"java","php","python","go"};

int type;

String BookName;

try {

type = searchType();

if(type == 1) {

BookName = searchBookName(books);

}else {

BookName = searchBookNum(books);

}

System.out.println("book:"+BookName);

}catch(BookException e) {

System.out.println(e.getMessage());

init();

}catch(Exception e) {

System.out.println(e.getMessage());

init();

}

}

//通过哪种类型选择图书

public int searchType() throws BookException {

Scanner input = new Scanner(System.in);//创建scanner对象

System.out.print("请输入命令:1-按照名称查找图书;2-按照序号查找图书");

int type = input.nextInt();

if(type == 1 || type == 2) {

return type;

}else{

throw new BookException("命令输入错误!请根据提示输入数字命令!");

}

}

//通过名称查找

public String searchBookName(String[] books) throws Exception {

Scanner input = new Scanner(System.in);//创建scanner对象

System.out.println("请输入图书名称:");

String BookName = input.next();

for(String book :  books) {

if(book.equals(BookName)) {

return BookName;

}

}


throw new Exception("图书不存在!");

}

//通过序号查找

public String searchBookNum(String[] books) throws Exception {

Scanner input = new Scanner(System.in);//创建scanner对象

System.out.println("请输入图书序号:");

int BookNum = input.nextInt();

if(BookNum < books.length && BookNum >= 0) {

return books[BookNum-1];

}

throw new Exception("图书不存在!");

}


}



package exception_demo;

public class BookException extends Exception{

public BookException(String message) {

super(message);

}

}


写回答 关注

2回答

  • 慕瓜7049329
    2020-03-14 19:32:45

    兄弟 我试了一下你的代码,有个问题

    下面这段里,当我int type输入非数字时,比如我控制台打一个a,为什么没有报InputMismatchException,你的代码运行结果是显示null,然后重新开始,这个我想不通啊


    //通过哪种类型选择图书

    public int searchType() throws BookException {

    Scanner input = new Scanner(System.in);//创建scanner对象

    System.out.print("请输入命令:1-按照名称查找图书;2-按照序号查找图书");

    int type = input.nextInt();

    if(type == 1 || type == 2) {

    return type;

    }else{

    throw new BookException("命令输入错误!请根据提示输入数字命令!");

    }

    }


  • 慕瓜7049329
    2020-03-13 12:21:53

    这个是不是没法实现报错之后重新输入?

    慕瓜7049...

    我错了。。。原来还可以这样 init()里面再init()

    2020-03-13 12:23:59

    共 1 条回复 >

Java入门第三季

Java中你必须懂得常用技能,不容错过的精彩,快来加入吧

409792 学习 · 4340 问题

查看课程

相似问题