2014-12-13 262 views
-3

的当我试图符合我得到这个错误:数组索引越界异常0

"Exception in thread "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; 

    } 
} 
+1

不,你在编译时没有遇到那个错误。 – chrylis 2014-12-13 05:30:30

回答

1

数组索引越界异常的一个for出现回路当它试图在这种情况下使用i的值并且i的值小于零时。

+0

编号'i'不能用作循环中的数组索引,它的初始值为1(而OP在数组索引0上有错误)。 – 2014-12-13 05:08:02

3

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

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

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