java菜鸟工程师
2019-05-07 19:14
package com.imooc.exception;
import java.util.Arrays;
import java.util.Scanner;
public class BorrowBook {
public static void main(String[] args) {
BorrowBook borrowBook=new BorrowBook();
borrowBook.Borrow();
}
public void Borrow(){
// 书号分别对应的是1,2,3,4
String[] books={"西游记","红楼梦","三国演义","水浒传"};
System.out.println("欢迎使用图书管理系统!");
System.out.println("1. 按照书名查找图书 2.按照序号查找图书");
Scanner input =new Scanner(System.in);
try {
int num=input.nextInt();
if (num==1){
System.out.println("请输入书名:");
Scanner input1=new Scanner(System.in);
String bookname=input1.nextLine();
boolean book= Arrays.asList(books).contains(bookname);
if (book==true){
System.out.println(bookname+"借书成功!");
}else {
throw new NoBookException("此书不存在");
}
}
if (num==2){
System.out.println("请输入书号:");
Scanner input2=new Scanner(System.in);
int shuhao=input2.nextInt();
if (shuhao>0 && shuhao<=books.length ){
System.out.println(books[shuhao-1]+"借书成功!");
}else{
throw new NoBookException("查无此书!");
}
}
}catch (NoBookException e){
System.out.println(e);
System.out.println();
Borrow();
}
}
}
你的shuhao应该>=0,就比如36行,应该这么写:if (shuhao>=0 && shuhao<books.length )。因为数组下标从0开始
这个序号是自动就给定好了的吗?
package com.imooc.exception; import java.util.Arrays;import java.util.Scanner; public class BorrowBook { public static void main(String[] args) { BorrowBook borrowBook=new BorrowBook(); borrowBook.Borrow(); } public void Borrow(){ // 书号分别对应的是1,2,3,4 String[] books={"西游记","红楼梦","三国演义","水浒传"}; System.out.println("欢迎使用图书管理系统!"); System.out.println("1. 按照书名查找图书 2.按照序号查找图书"); Scanner input =new Scanner(System.in); try { int num=input.nextInt(); if (num==1){ System.out.println("请输入书名:"); Scanner input1=new Scanner(System.in); String bookname=input1.nextLine(); boolean book= Arrays.asList(books).contains(bookname); if (book==true){ System.out.println(bookname+"借书成功!"); }else { throw new NoBookException("此书不存在"); } } if (num==2){ System.out.println("请输入书号:"); Scanner input2=new Scanner(System.in); int shuhao=input2.nextInt(); if (shuhao>0 && shuhao<=books.length ){ System.out.println(books[shuhao-1]+"借书成功!"); }else{ throw new NoBookException("查无此书!"); } } }catch (NoBookException e){ System.out.println(e); System.out.println(); Borrow(); } }}
你这个已经挺简单了,要是借书前加个循环输出都有哪些书号+书名,就更好了
Java入门第三季
409775 学习 · 4546 问题
相似问题