Home>
package prog;
public class kadai0903 {
    static double getRandomDouble (double low, double high) {
        double ans = 0.0;
        double r = Math.random ();
        ans = low + r * (high-low);
        return ans;
    }
    static int getRandomInt (int low, int high) {
        int ans = 0;
        ans = (int) getRandomDouble (low, high);
        return ans;
    }
    public static void main (String [] args) {
        int i, total;
        int [] d = {0,0,0,0,0,0,0,0,0,0,0};
        i = 0;
        total = 0;
        double n = 1000000;
        int v;
        int [] cnt = new int [10 + 1];
        while (i<n) {
            int x = getRandomInt (0, 6);
            int y = getRandomInt (0, 6);
            total = x + y;
            d [total] ++;
            i ++;
            v = d [total];
            try {
                cnt [v] ++;
                } catch (Exception e) {
                System.out.printf ("Impossible value% d was in index% d \ n", v, i);
                }
        }
        System.out.println ("2" + "" + d [0] + "" + d [0]/n);
        System.out.println ("3" + "" + d [1] + "" + d [1]/n);
        System.out.println ("4" + "" + d [2] + "" + d [2]/n);
        System.out.println ("5" + "" + d [3] + "" + d [3]/n);
        System.out.println ("6" + "" + d [4] + "" + d [4]/n);
        System.out.println ("7" + "" + d [5] + "" + d [5]/n);
        System.out.println ("8" + "" + d [6] + "" + d [6]/n);
        System.out.println ("9" + "" + d [7] + "" + d [7]/n);
        System.out.println ("10" + "" + d [8] + "" + d [8]/n);
        System.out.println ("11" + "" + d [9] + "" + d [9]/n);
        System.out.println ("12" + "" + d [10] + "" + d [10]/n);
    }
}


I want to modify the above program to catch an exception for out-of-array reference and terminate the program when the exception is caught.
I put the try and catch parts as out-of-array references, but I want to fix this.
I didn't know what to try

  • Answer # 1

    Did you refer to the outside of the array with d [total]?
    If d [11] appears, it's out.
    If you want to check with try-catch, this is also the place. Well, I think we should do something when we decide the total ...