-1

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;

    }
}
1
  • 1
    No, you aren't getting that error when you compile. Commented Dec 13, 2014 at 5:30

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

Comments

1

Array Index Out Of Bounds Exception occurs in a for loop when it attempts to use the value of i in this case and the value of i is less than zero.

1 Comment

No. i is not used as an array index in that for loop, and it has an initial value of 1 (while OP has an error on array index 0).
0

java.lang.ArrayIndexOutOfBoundsException: 0 is self explanatory args[0] position of array is not having value, that's why int trials = Integer.parseInt(args[0]); line throwing exception, you have to pass argument to your program.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.