Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Contoh exception handling pada program pembagian.
- *
- * @author David Ralphwaldo Martuaraja
- * @version 28 Desember 2020
- */
- import java.util.Scanner;
- import java.util.InputMismatchException;
- public class ExceptionHandling
- {
- public static void main(String[] args)
- {
- Scanner scanner = new Scanner(System.in);
- boolean inputLoop1 = true, inputLoop2 = true;
- int num1 = 0, num2 = 0;
- System.out.println("== Program pembagian sederhana ==");
- System.out.println();
- do
- {
- try
- {
- System.out.print("Masukkan angka pertama> ");
- num1 = scanner.nextInt();
- inputLoop1 = false;
- } catch (InputMismatchException e) {
- System.err.println("Exception: " + e);
- System.out.println("Masukkan sebuah angka!");
- scanner.nextLine();
- }
- } while(inputLoop1);
- inputLoop1 = true;
- do
- {
- try
- {
- do
- {
- try
- {
- System.out.print("Masukkan angka kedua> ");
- num2 = scanner.nextInt();
- inputLoop1 = false;
- } catch (InputMismatchException e) {
- System.err.println("Exception: " + e);
- System.out.println("Masukkan sebuah angka!");
- scanner.nextLine();
- }
- } while(inputLoop1);
- System.out.println("Hasil dari " + num1 + " / " + num2 + " = " + (num1 / num2));
- inputLoop2 = false;
- } catch (ArithmeticException ae) {
- System.err.println("Exception: " + ae);
- System.out.println("Pembagian angka dengan nol!");
- scanner.nextLine();
- inputLoop1 = true;
- }
- } while(inputLoop2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment