数组索引超出界限0

时间:2014-12-13 05:04:22

标签: java arrays indexoutofboundsexception

当我尝试遵守时,我收到此错误:

  

"线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:0"

我不知道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;

    }
}

3 个答案:

答案 0 :(得分:3)

运行程序时未指定任何参数,因此args[0]不是有效索引。

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

答案 1 :(得分:1)

数组索引超出界限当for循环尝试在此情况下使用i的值并且i的值小于零时,会发生异常。

答案 2 :(得分:0)

java.lang.ArrayIndexOutOfBoundsException: 0是自解释args[0]数组的位置没有值,这就是int trials = Integer.parseInt(args[0]);行抛出异常的原因,你必须将参数传递给你的程序。