Java 数组索引越界异常 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27455742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:24:09  来源:igfitidea点击:

Array Index out of Bounds Exception 0

javaarraysindexoutofboundsexception

提问by bhsingh

When I try to comply I get this Error:

当我尝试遵守时,出现此错误:

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

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

I do not know hy

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

    }
}

回答by SemperAmbroscus

Array Index Out Of Bounds Exception occurs in a forloop when it attempts to use the value of iin this case and the value of iis less than zero.

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

回答by Elliott Frisch

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

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

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

回答by atish shimpi

java.lang.ArrayIndexOutOfBoundsException: 0is 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.

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