java 异常练习题_java入门异常处理练习题问题
tppe
大概方式:1、判斷用戶輸入的類型是否正確,不正確捕獲異常,把他包裝成我自己定義的異常2、判斷用戶輸入的數(shù)是多少2.1、如果是1,則打印“輸入圖書名稱”,用戶輸入,定義一個(gè)Book類型的數(shù)組,然后遍歷,定義一個(gè)計(jì)數(shù)器count,如果用戶輸入的值等于數(shù)組遍歷的值(書的名字不能重復(fù),此處有錯(cuò)誤,因?yàn)槿绻种貜?fù)的話,輸入名字應(yīng)該同時(shí)出現(xiàn)重復(fù)的書名和不同的書號(hào)(自動(dòng)默認(rèn)書號(hào)是不能重復(fù)的)),計(jì)數(shù)器加1,這里如果計(jì)數(shù)器不等于1的話(有兩個(gè)原因:(1)大于1:可能是出現(xiàn)了重復(fù)的書名 (2)等于0:可能是不存在這本書 (3)小于0:不知道了。。。),但是我這邊是不管是哪種原因,我都是用的“圖書不存在”這個(gè)異常,所以也有問題2.2、如果是2:同上整個(gè)有點(diǎn)混亂,還有好多問題1、package com.library;public class Book {private String bookName;private int lNum;public Book() {super();// TODO Auto-generated constructor stub}public Book(String bookName, int num) {super();this.bookName = bookName;lNum = num;}public String getBookName() {return bookName;}public int getLNum() {return lNum;}}2、package com.library;public class MyException extends Exception{public MyException(){}public MyException(String message){super(message);}}3、package com.library;import java.util.Scanner;public class TestLibrary {private static TestLibrary tl;public static void main(String[] args) {tl = new TestLibrary();System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號(hào)查找圖書");try {tl.test2();} catch (MyException e) {// TODO Auto-generated catch blocke.printStackTrace();for(int i = 1; i != 0; i++){System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號(hào)查找圖書");try {tl.test2();} catch (MyException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}}?public void test2() throws MyException{Book book1 = new Book("數(shù)據(jù)結(jié)構(gòu)",1);Book book2 = new Book("高數(shù)",2);//Book book3 = new Book("高數(shù)",3);Book[] library = {book1,book2};try {Scanner s = new Scanner(System.in);Integer input = s.nextInt();if((input instanceof Integer) == true){?if(input.equals(1)){int count = 0;System.out.println("輸入圖書名稱");Scanner s1 = new Scanner(System.in);String bookName = s1.nextLine();for(int i = 0; i < library.length; i++){if(bookName.equals(library[i].getBookName())){System.out.println("book:" + library[i].getBookName());count++;//System.out.println(count+"...");}}?if(count != 1){tl.test4();}}else if(input.equals(2)){int count = 0;System.out.println("輸入圖書序號(hào)");Scanner s2 = new Scanner(System.in);int lNum = s2.nextInt();for(int i = 0; i < library.length; i++){if(lNum == (library[i].getLNum())){System.out.println("book:" + library[i].getBookName());count++;}}if(count != 1){tl.test4();}}}} catch (Exception e){MyException exception = new MyException("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示輸入數(shù)字命令");exception.initCause(e);throw exception;}}?// public void test1() throws MyException { throw new MyException("命令輸入錯(cuò)誤!請(qǐng)根據(jù)提示輸入數(shù)字命令");// }?public void test3() throws MyException{?throw new MyException("圖書不存在");}?public void test4(){try {test3();} catch (MyException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
總結(jié)
以上是生活随笔為你收集整理的java 异常练习题_java入门异常处理练习题问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 取消外地施工企业备案流程(取消外地施工企
- 下一篇: java 框架 例子_如何设计Java框