求救。為什么不管是符合要求的還是不符合要求的,數(shù)組中的書名都不會出來,一直報異常。不懂啊
package exception_test;
import java.util.*;//導(dǎo)入java工具
public class Test_Exception {
/*圖書查找程序:
?* 1.提示用戶輸入,分別按書名及圖書序號來查找圖書
?* 2.根據(jù)輸入信息進(jìn)行適當(dāng)?shù)漠惓L幚?br />?*/
?? ?public static void main(String[] args) {
?? ??? ?// TODO Auto-generated method stub
?? ??? ?show();
?? ??? ?
?? ??? ?
?? ?}
?? ?public static void books(String bookname){
?? ??? ?String[] book={"論語","高數(shù)","日語","英語","漢語"};
?? ??? ?
?? ??? ?try{
?? ??? ??? ?for(int i =0;i<book.length;i++){
?? ??? ??? ?if(book[i].equals(bookname)){
?? ??? ??? ??? ?System.out.println("book:"+book[i]);
?? ??? ??? ?}else {
?? ??? ??? ??? ?throw new Exception();
?? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?}catch (Exception e){
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("您查詢的書名不存在: "+"\n" + "如有需要請重新選擇:");?? ?
?? ??? ??? ?show();
?? ??? ?}
?? ?}
?? ?public static void bookNum(int BookNum){
?? ??? ?String[] book={"論語","高數(shù)","日語","英語","漢語"};
?? ??? ?try{
?? ??? ??? ?int bookNum =0;
?? ??? ??? ?if(bookNum >0 && bookNum<book.length){
?? ??? ??? ??? ?System.out.println("book:"+book[bookNum-1]);
?? ??? ??? ?}else{
?? ??? ??? ??? ?throw new Exception();
?? ??? ??? ?}
?? ??? ?}catch(Exception e){
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("您查詢的書籍不存在: "+"\n" + "如有需要請重新選擇:");?? ?
?? ??? ??? ?show();
?? ??? ?}
?? ?}
?? ?public static void bookname(String name){
?? ??? ?Scanner input2 = new Scanner(System.in);
?? ??? ?try{
?? ??? ??? ?System.out.println("請輸入您所需的書名:");
?? ??? ??? ?String name1 =input2.next();
?? ??? ??? ?books(name1);
?? ??? ?}catch(Exception e){
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("請重新輸入書名:");
?? ??? ??? ?return;
?? ??? ?}
?? ?}
?? ??? ?
?? ?public static void booknum(int num){
?? ??? ?Scanner input3 = new Scanner(System.in);
?? ??? ?try{
?? ??? ??? ?System.out.println("請輸入您所需的書號:");
?? ??? ??? ?int n =input3.nextInt();
?? ??? ??? ?bookNum(n);
?? ??? ?}catch(Exception e){
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("請重新輸入書號:");
?? ??? ??? ?return;
?? ??? ?}
?? ?}
?? ?
?? ?public static void show(){
?? ??? ?System.out.println("歡迎您來到閱讀快樂吧:書名查詢請選1;序號查詢請選2");
?? ??? ?Scanner input =new Scanner(System.in);
?? ??? ?int Num =input.nextInt();
?? ??? ?try{
?? ??? ??? if(Num ==1){
?? ??? ??? ?bookname(null);
?? ??? ?? }else if (Num==2){
?? ??? ??? ?booknum(Num);
?? ??? ?? }else{
?? ??? ??? ?? throw new Exception();
?? ??? ?? }
?? ??? }catch(Exception e){
?? ??? ? System.out.println("您輸入的信息有誤,請重新輸入:");
?? ??? ? show();
?? ????? }
???? }
}
2019-04-30
??try{
?? ??? ??? ?for(int i =0;i<book.length;i++){
?? ??? ??? ?if(book[i].equals(bookname)){
?? ??? ??? ??? ?System.out.println("book:"+book[i]);
?? ??? ??? ?}else {
?? ??? ??? ??? ?throw new Exception();
?? ??? ??? ?}
這一段,每次循環(huán)比較如果不equals,就會throw new Exception();,你這樣當(dāng)然會報異常啊
2019-05-21
順便定義一個變量j,當(dāng)出現(xiàn)相同的情況時,變量值變一下,如果沒變就是異常