-3

私はこのエラーを言っています

java.lang.ArrayIndexOutOfBoundsException: 2
    at J4.writefile(J4_2_MultiDimensionalArray7.java:30)
    at J4.main(J4_2_MultiDimensionalArray7.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

このエラーはどういう意味ですか? 私のプログラムは、プログラムによって生成された座標を別のファイルに書き込むことです。プログラムはコンパイルされますが、実行されません。このエラーを修正するにはどうすればよいですか?

ありがとう!

コードは次のとおりです。

import java.io.*;
import java.util.Arrays;

public class J4
{
    public static void main (String [] args) throws IOException
    {
        int numpoints = 100, dimension = 2, length = 100;//numpoints is set to 100, dimension is set to 2, length is set to 100

        //arrays are initializewd and declared
        double [] lengthscale = new double [dimension];
        double [][] locations = new double [numpoints][dimension];

        PrintWriter fileOut = new PrintWriter (new FileWriter ("arrayNumPoints.txt"));

        writefile(lengthscale, locations, numpoints, dimension, length);


        for(int m=0; m <length; m++){//for loop
            fileOut.println(Arrays.toString(locations[m]) + ", ");//writes to file
        }
        fileOut.close ();//close file

    }//end main

    public static Double writefile(double lengthscale[], double locations[][], int dimension, int numpoints, int length)throws IOException
    {

        for (int a = 0; a < dimension; a++){//for loop runs while a is less than dimension
            lengthscale[a] = length;//stores array
        }//end for loop

        for (int x=0; x < numpoints; x++){//for loop runs while x is less than numpoints
            for (int y=0; y < dimension; y++){//nested for loop runs while y is less than dimension
                locations [x][y]= (2 * Math.random() - 1) * lengthscale[y];//creates the range and choses random point within 
                return locations[x][y];

            }//end nested for loop
        }//end for loop

        //if program doesnt run through loop.. alternative return statement (but
        double b= 1;    
        return b;
    }//end writefile methos
}//end 

なぜこうなった?

4

2 に答える 2

0

コードを見なくても2、配列のインデックスにアクセスしようとしていることがわかります。範囲外であるため、配列の長さは2以下でなければなりません。0有効な配列インデックスは~であることを思い出してくださいlength - 1

于 2013-09-23T22:59:42.827 に答える