Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: java.lang.ArrayIndexOutOfBoundsException error

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    12
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default java.lang.ArrayIndexOutOfBoundsException error

    I have an object and client class created which prints coordinates in order of their distance from the origin. The client class asks the user how many dimensions they want the array to have (x,y or x,y,z) how many points they want generated, and a range from which each coordinate will run from (ex. -x to x, -y to y etc.). When I run the program with out the sortArray methods, it prints the correct points. (the distance is the last element of the coordinate). However, when I add the sortArray method to the client class, it allows me to enter the information but gives me the error:
    java.lang.ArrayIndexOutOfBoundsException: 5
    	at arrayObjects.sortArray(arrayObjects.java:130)
    	at arrayClass.main(arrayClass.java:34)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	at java.lang.reflect.Method.invoke(Method.java:597)
    	at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
    arrayClass
    import java.io.*;
     
    public class arrayClass
    {
      public static void main (String [] args) throws IOException
      {
        BufferedReader myInput = new BufferedReader (new InputStreamReader(System.in));
     
        int points = 0, dimension = 0;
        double lengthA = 0;
     
        double dataPoints [][] = new double [points][dimension + 1];
     
        System.out.println("How many dimensions do you want?");
        String dimensionA = myInput.readLine();
        dimension = Integer.parseInt(dimensionA);
     
        System.out.println("How many points do you want?");
        String pointsA = myInput.readLine();
        points = Integer.parseInt(pointsA);
     
        System.out.println("Enter a range: ");
        String lengthB = myInput.readLine();
        lengthA = Double.parseDouble(lengthB);
     
        arrayObjects objects;
     
        String myString = "arrayPoints.txt";
     
        objects = new arrayObjects(lengthA, points, dimension, dataPoints);
        objects.fillArray(objects.getArray(), objects.getRange(), objects.getDimension(), objects.getNumPoints());
        objects.findDistance(objects.getArray(), objects.getNumPoints(), objects.getDimension()); 
        objects.sortArray(objects.getArray(), objects.getDimension(), 0, objects.getNumPoints());
        objects.writeData(objects.getArray(), objects.getNumPoints(), myString);
        objects.readData(myString);
     
     
     
     
      }//end main method
    }

    arrayObjects class
    import java.io.*;
    import java.util.Arrays;
     
    public class arrayObjects
    {
      private int dimension;
      private double lengthA;
      private int points;
      private double [][] dataPoints;
     
      //empty constructor
      public arrayObjects(){
      }
      //constructor
      public arrayObjects(double[][] datapoints)
      {
        lengthA = 0;
        points = 0;
        dimension = 0;
        this.dataPoints = new double [points][dimension +1];
         }
      //constructor
      public arrayObjects(double myLength, int myPoints, int myDimension, double[][] dataPoints){
        lengthA = myLength;
        points = myPoints;
        dimension = myDimension;
        this.dataPoints = new double [points][dimension + 1];
         }
      //array getter
      public double[][] getArray(){
        //findDistance(dataPoints, points, dimension);
        return dataPoints;
      }
     //array setter
      public void setArray(double [][] myDataPoints, int dimension, int points){
        dataPoints[points][dimension] = myDataPoints[points][dimension];
      }
      //dimension getter
      public int getDimension(){
        return dimension;
      }
      //dimension setter
      public void setDimension(int myDimension){
        dimension = myDimension;
      }
      //points getter
      public int getNumPoints(){
        return points;
      }
      //points setter
      public void setNumPoints(int myNumPoints){
        points = myNumPoints;
      }
      //range getter
      public double getRange(){
        return lengthA;
      }
      //range setter
      public void setRange(double myRange){
        lengthA = myRange;
      }
      //fill arrays with values
      public void fillArray(double [][] mydataPoints, double mylengthA, int mydimension, int mypoints)throws IOException
      {
        for(int x = 0; x < mypoints; x++){//runs x times to print x data points
          for (int y = 0; y < mydimension; y++){//runs y times to print a coordinate
            mydataPoints [x][y]= (dimension *Math.random() - 1) * mylengthA;// finds a random number in the range and assigns it to the coordinate array
          }//end for
        }//end for
        }//end fillArray
      //reads data from file
      public void readData(String myString)throws IOException
      {
        BufferedReader readfile = new BufferedReader(new FileReader(myString));//reads data from arrayPoints.txt
        try {//try statement
          StringBuilder file = new StringBuilder();
          String line = readfile.readLine();//assigns line data from file
     
          while (line != null) {//run while line isn't empty
            file.append(line);
            file.append('\n');
            line = readfile.readLine();
          }//end while
          String finalData = file.toString();//converts to a string
          System.out.print(finalData);//prints the coordinate
        } //end try
        finally {//close file when done
          readfile.close();
        }//end finally
      }//end readFile
      //write data to a file
      public void writeData(double[][] mydataPoints, int mypoints, String myString)throws IOException
      {
        PrintWriter fileOut = new PrintWriter (new FileWriter (myString));//writes to myString file
        for (int i = 0; i < mypoints; i++){
          fileOut.println(Arrays.toString(mydataPoints[i]));//converts array to string and prints to file
        }//end for
        fileOut.close();//writes to file
      }//end writeData
     
      //calculates distance between coordinates
      public void findDistance(double[][] mydataPoints, int mypoints, int mydimension){
     
        for(int i = 0; i < mypoints; i++){
          for (int j = 0; j < mydimension; j++){
            mydataPoints[i][mydimension] = mydataPoints[i][j] * mydataPoints[i][j];//calculaes distance using distane formula
          }
          mydataPoints[i][mydimension] = Math.sqrt(mydataPoints[i][mydimension]);
          }//end for
     
        }//end findDistance
     
      //quick sort for array
      public double[][] sortArray(double[][] newArray, int mydimension, int down, int top) {
     
     
        System.arraycopy(newArray, 0, newArray, 0, newArray.length);
     
        int i = down;//sets int variables
        int j = top;
        double [] pivot = newArray[(down + top) / 2];//finds centre pivot point
     
        //goes through each value and sorts depending if its greater or less than the pivot point
        do {
          while (newArray[i][mydimension] < pivot[mydimension]) {
            i++;
          }
     
          while (newArray[j][mydimension] > pivot[mydimension]) {
            j--;
          }
     
          if (i <= j) {
            double[] temp = new double[newArray[i].length];
     
            for (int y = 0; y < newArray[i].length; y++) {
              temp[y] = newArray[i][y];
              newArray[i][y] = newArray[j][y];
              newArray[j][y] = temp[y];
            }
                i++;
            j--;
          }
        } while (i <= j);
     
        if (down < j) {
          newArray = sortArray(newArray, mydimension, down, j);
        }
     
        if (i < top) {
          newArray = sortArray(newArray, mydimension, i, top);
        }
        //returns array
        return newArray;
      }//end sortArray
    }


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: java.lang.ArrayIndexOutOfBoundsException error

    You have a lot of loops going on.
    The exception is thrown on line 130 of the arrayObjects class (according to your stack trace). What is on that line?
    I don't know if you are doing this or not, but remember that the indexes of an array start at 0 and end at the array's length minus 1 (the array's length is not a valid index).
    So if you had an array of length 5, array[5] would throw an index out of bounds exception. The indexes for that array would be 0 to 4, inclusively.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Sep 2013
    Posts
    12
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: java.lang.ArrayIndexOutOfBoundsException error

    Quote Originally Posted by aussiemcgr View Post
    The exception is thrown on line 130 of the arrayObjects class (according to your stack trace). What is on that line?
    This is what is on that line:
    while (newArray[j][mydimension] > pivot[mydimension]) {
            j--;
          }
    I believe my problem may be when I add 1 to the dimensions in the constructors, however when I remove it I still get an out of bounds error. Do you know why this is happening?

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: java.lang.ArrayIndexOutOfBoundsException error

    Ok, so for the sake of learning, I will go over with you every step in the process of debugging an issue like this. If I lose you anywhere, feel free to ask me to clarify:
    We know there are 3 index references on that line, so we have a handful of different possibilities (j and mydimension twice). However, the while loop before is almost the same, with the only exception of the use of i instead of j. If the mydimension variable caused the index out of bounds exception, it should have happened on the previous while loop, not this one. That would mean that j must to be the offending variable. Since j is always decreasing, we know that the exception must be happening on the first evaluation of the while loop condition, suggesting that the initial value of j is the problem.
    In this method, j is initialized by the int parameter variable: top. There are no more modifications of the variable between there and our while loop, so the value being passed in the top variable is the problem. Going back to our stack trace, we see that the method which invoked the sortArray() method was the main (line 34).
    An observation of the main makes it obvious which line 34 is (the only one which calls sortArray()). The value of the top parameter value is being set to: objects.getNumPoints(), so this value is the problem. The newArray parameter variable is also being passed from that line. Going back to the arrayObjects class, getNumPoints() is just a getter, so we need to look for when the variable was set to determine its value. No methods in the arrayObjects class appear to alter that value, so that suggests the value is being set by the main using either the setter or the constructor. The setter is never used in the main, but the constructor is passed a value for the points variable. Also in the constructor, we set the size of the dataPoints array. The dataPoints array is the one being sent to the sortArray() method, along with the points variable. The length of the dataPoints array is equal to the value of the points variable (according to your constructor). As I pointed out in an earlier post, the length of an array is not a valid index, which is why you are getting your problem.

    So, how to fix it? The last index in the dataPoints array will be points-1. Since you are assuming the top variable in the sortArray() method to be the largest index, you would want to make the following change in your main.
    Change this:
    objects.sortArray(objects.getArray(), objects.getDimension(), 0, objects.getNumPoints());
    to this:
    objects.sortArray(objects.getArray(), objects.getDimension(), 0, objects.getNumPoints()-1);

    Give that a try and see what happens.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    incxx (October 30th, 2013)

  6. #5
    Junior Member
    Join Date
    Sep 2013
    Posts
    12
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: java.lang.ArrayIndexOutOfBoundsException error

    I understand why that was happening now! Thank you so much for your explanation, it helped a lot. I have applied your corrections and it works perfectly. Thanks!

Similar Threads

  1. Error message java.lang.ArrayIndexOutOfBoundsException: 0
    By EDale in forum What's Wrong With My Code?
    Replies: 7
    Last Post: March 27th, 2013, 08:16 PM
  2. (java.lang.NumberFormatException: null) error
    By vishnuib2000 in forum JavaServer Pages: JSP & JSTL
    Replies: 1
    Last Post: April 2nd, 2012, 08:09 AM
  3. [SOLVED] Java run time error: 'java.lang.NullPointerException"
    By ChandanSharma in forum What's Wrong With My Code?
    Replies: 9
    Last Post: June 20th, 2011, 11:53 AM
  4. java.lang.numberformatexception error
    By natalie in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 19th, 2010, 04:16 AM
  5. Replies: 2
    Last Post: November 3rd, 2009, 06:28 AM