简体   繁体   中英

java- using try-catch in the search algorithm error

i've got a problem when i use try-catch in the search method. when i input the wrong data, it just skips the catch block and output the code below it

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.

The InputMismatchException is potentially thrown by Scanner 's methods. You need to include them in the try block:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM