手记

异常的代码书写,还是有点不懂

package firstSaample;

import java.util.ArrayList;
import java.util.Scanner;

public class demo {

public static void main (String[]args) 
{ 
      NewLibrary library=new NewLibrary();
      Scanner scanner=new Scanner(System.in);
  while(true)
  {
     try{
        int estimate=scanner.nextInt();
        library.getCommand(estimate);
        if(estimate==1)
        {
             try {  
        String estimate1=scanner.next();
        library.bookSequence(estimate1);break;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        System.out.println(e.toString());
    }        
        }
        if(estimate==2)
        {
             try {  
        String estimate1=scanner.next();
        library.bookTitle(estimate1); break;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        System.out.println(e.toString());
    } 

        }
     } catch(Exception e){
         System.out.println(e.toString());
     }
  } 

}

}

定义的异常类
package firstSaample;
import java.util.ArrayList;
public class NewLibrary extends Exception
{
private ArrayList<String> arr=new ArrayList<String>();
public NewLibrary()
{
arr.add("论语");
arr.add("史记");
arr.add("东周列国志");
arr.add("java核心思想");
arr.add("java疯狂讲义");
arr.add("程序员的自我修养");
arr.add("高等数学");
arr.add("简爱英文");
System.out.print("1-按照图书名称查找;2-按照图书序号查找 ");
}
public void getCommand(int i) throws Exception
{
if(i!=1&&i!=2)
throw new Exception("命令输入错误请根据提醒输入命令 "+"1-按照图书名称查找;2-按照图书序号查找");

        else
        {
            if(i==2)
            System.out.println("请输入书名");
            if(i==1)
                System.out.println("请输入书的序号");
        }
    }

    public void bookTitle (String bookTitle) throws Exception
    {
        if(arr.indexOf(bookTitle)==-1)          
        throw new Exception("图书不存在  "+"1-按照图书名称查找;2-按照图书序号查找");
        else
            System.out.println("book:"+bookTitle);
    }

    public void bookSequence(String bookNum) throws Exception
    {
        if(arr.size()<Integer.parseInt(bookNum)Integer.parseInt(bookNum)<0)
        throw new Exception("图书不存在  "+"1-按照图书名称查找;2-按照图书序号查找");
        else
            System.out.println("book:"+arr.get(Integer.parseInt(bookNum)));
    }

}
2人推荐
随时随地看视频
慕课网APP