簡體   English   中英

java-在搜索算法錯誤中使用try-catch

[英]java- using try-catch in the search algorithm error

我在搜索方法中使用 try-catch 時遇到問題。 當我輸入錯誤的數據時,它只是跳過 catch 塊並輸出它下面的代碼

do {
            System.out.print(menu[1]);
            jumlah = sc1.nextInt();
            System.out.print(menu[0]);
            tujuan = sc1.nextInt();
            for (int i = 0; i < DataRek.length; i++) {
                try {
                    if (tujuan == DataRek[i]) {
                        index = i;
                        nasabah = NamaRek[index];
                        break;
                    }
                } catch (InputMismatchException e) {
                    System.out.println("DATA NASABAH TIDAK DITEMUKAN, SILAHKAN COBA LAGI");
                    System.exit(0);
                }
            }
        } while (loop2 == 1);
        System.out.println("Nomor rekening tujuan: " + tujuan);
        System.out.println("Nama Nasabah: " + nasabah);
        System.out.println("Jumlah yang ditransfer: " + jumlah);
        System.out.println("Apakah data diatas sudah benar? (Y/N) ");
        loop1 = sc1.next().charAt(0);

當我輸入錯誤的數據時,我期望 DATA NASABAH TIDAK DITEMUKAN 的輸出,但實際輸出是它下面的代碼。

InputMismatchException可能由Scanner的方法拋出。 您需要將它們包含在try塊中:

do {
    try {
        System.out.print(menu[1]);
        jumlah = sc1.nextInt();
        System.out.print(menu[0]);
        tujuan = sc1.nextInt();
        for (int i = 0; i < DataRek.length; i++) {    
            if (tujuan == DataRek[i]) {
                index = i;
                nasabah = NamaRek[index];
                break;
            }
        }
    } catch (InputMismatchException e) {
        System.out.println("DATA NASABAH TIDAK DITEMUKAN, SILAHKAN COBA LAGI");
        System.exit(0);
    }
} while (loop2 == 1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM