【问题标题】:Array Index out of Bounds Exception 0 [duplicate]数组索引超出范围异常0 [重复]
【发布时间】:2015-02-11 21:04:52
【问题描述】:

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

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

我不知道

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;

    }
}

【问题讨论】:

  • 不,编译时不会出现该错误。

标签: java arrays indexoutofboundsexception


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在这种情况下,for 尝试使用 i 的值并且 i 的值小于零时,会在 for 循环中发生数组索引越界异常。

    【讨论】:

    • 没有。 i 在该 for 循环中不用作数组索引,它的初始值为 1(而 OP 在数组索引 0 上有错误)。
    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 2016-05-03
      • 2017-10-05
      • 2012-11-01
      相关资源
      最近更新 更多