LoginSignup
0
0

More than 3 years have passed since last update.

例外処理の練習(ArithmeticException)

Posted at
ThrowsExam.java
package JavaStudy;
import java.util.Scanner;
//整数を入力された値で割る処理
//0で割る場合は例外処理
public class ThrowsExam {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int a = 6873;
        int retry = 0 ;
        System.out.println("プログラムを開始します");
        do {            

            System.out.print("数値を入力してください。");
            try{
                int b = scan.nextInt();
                double c = divide(a,b);
                System.out.println(c);
            }catch(ArithmeticException e) {
                e.printStackTrace(); //エラーの経路・内容を表示
                System.out.println("入力値は0より大きい必要があります。");

            }
            do { //リトライの数値が0、1以外の時は繰りかえし
                System.out.print("Retry? [1 = yes / 0 = no]");
                retry = scan.nextInt();
                if(retry>1)
                    System.out.println("無効な数値が入力されました。");
            }while(!(retry <= 1 && retry >= 0));

        }while(retry == 1);
        System.out.println("プログラムを終了します");
    }

    public static double divide(int a, int b) throws ArithmeticException  {
        return a / b;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0