Java – Array Index out of Bounds Exception 0

arraysindexoutofboundsexceptionjava

When I try to comply I get this Error:

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0"

I do not know hy

package Darts;

import java.util.Random;
import static java.lang.Integer.*;

/**
 * Created by BryanSingh on 12/12/14.
 * Dartsim.java
 *
 */

public class DartSim
{
    public static void main(String[] args)    
    {
        //int trials = 0;
        int trials = Integer.parseInt(args[0]);

        DartSim myDart = new DartSim();

        for (int i=1; i<=trials; i++)
        {
            myDart.toss();
            System.out.println("pi = " + 4.0 * (double) myDart.getHits() / myDart.getThrows());
        }
    }

    private int hits;
    private int tries;
    private Random gen;

    public DartSim()
    {
        hits = 0;
        tries = 0;
        gen = new Random();
    }

    public void toss()
    {
        double x = 2 * gen.nextDouble() - 1;
        double y = 2 * gen.nextDouble() - 1;

        if(x*x+y*y<1)
        {
            hits = hits +1;
        }
        tries = tries +1;
    }

    public int getHits()
    {
        return hits;
    }

    public int getThrows()
    {
        return tries;

    }
}

Best Solution

You aren't specifying any arguments when you run the program so args[0] isn't a valid index.

// to use 10 when there aren't args...
int trials = (args.length > 0) ? Integer.parseInt(args[0]) : 10;