C_Hui
2016-09-22 11:06:39浏览 2208
在调用Book类的方法中不能使用scanner的close方法,不然会在main中出现异常,有人知道为什么吗?
import java.util.Scanner;
public class BookSystem {
public static void main(String[] args){
Book books=new Book();
int i=1;
System.out.println("序号"+"\t"+"书名");
for(String name : books.getBooks()){
System.out.println(i+"\t"+name);
i++;
}
boolean exit = false;
Scanner sc = new Scanner(System.in);
while(!exit){
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书;0-退出");
String j = sc.next();
try{
switch(j){
case "0": exit=true;
break;
case "1": books.findByName();
break;
case "2": books.findByNum();
break;
default : throw new Exception(); //如果都不匹配,就抛出异常
}
}catch(Exception e){
System.out.println("命令输入错误!请根据提示输入数字命令!");
}
}
sc.close();
}
}
public class Book {
private String[] books={"语文","英语","数学","地理","政治","生物"};
public String[] getBooks() {
return books;
}
public void findByName(){
Scanner sc = new Scanner(System.in);
System.out.println("输入图书名称:");
String name = sc.next();
try {
for (String bookname : books) {
if(bookname.equals(name)){
System.out.println("book:"+name);
//sc.close();不知道为什么不能关闭,不然就会出现异常。。。
return; //如果找到图书,就直接返回
}
}
throw new Exception(); //如果没找到图书,就抛出图书不存在的异常
}catch(Exception e){
System.out.println("图书不存在!");
//sc.close();
}
}
public void findByNum(){
Scanner sc = new Scanner(System.in);
System.out.println("输入图书序号:");
try{
int i = sc.nextInt(); //如果输入的不是整数,就会抛出InputMismatchException
if(i<0i>books.length){
System.out.println("图书不存在");
//sc.close();
return;
}
System.out.println("book:"+books[i-1]);
}catch (java.util.InputMismatchException e){ //可以直接捕获Exception
System.out.println("命令输入错误!请按照提示输入数字命令");
}
//sc.close();
}
}