简体   繁体   English

java-在搜索算法错误中使用try-catch

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

i've got a problem when i use try-catch in the search method.我在搜索方法中使用 try-catch 时遇到问题。 when i input the wrong data, it just skips the catch block and output the code below it当我输入错误的数据时,它只是跳过 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);

when i input the wrong data, i expect the output of DATA NASABAH TIDAK DITEMUKAN, but the actual output is the code below it.当我输入错误的数据时,我期望 DATA NASABAH TIDAK DITEMUKAN 的输出,但实际输出是它下面的代码。

The InputMismatchException is potentially thrown by Scanner 's methods. InputMismatchException可能由Scanner的方法抛出。 You need to include them in the try block:您需要将它们包含在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