0

I am trying to write a method that takes a 2D array parameter and creates from it a 1D array with a length equal to the number of rows in the original array. I also want the elements in the rows of the new array to equal the minimum value from each row of the original array. If the original row is empty, I’d like to have the new array equal 0.0. I’ve written my method below but I am receiving an indexOutOfBounds error and I’m not sure why…. Thanks

enter  public double[] newOneD(double[][] x) {
int xrow = x.length;
int xcol = x[0].length;
double[] y = new double[xrow];  
int min = 0;
for (int i = 0; i < xrow; i++){ 
    for (int j = 0; j < xcol; j++) {
        if(x[i][j] < x[i][min]) {min = j;}
        y[i] = x[i][min];}
}
return y;}
TacoB2018
  • 33
  • 5
  • Take a look at https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems – clinomaniac Mar 16 '18 at 18:45

1 Answers1

1

Your error is caused by the fact that you're assuming the number of columns in each row is equal to the number of columns in first row:

int xcol = x[0].length; //this is an assumption that doesn't hold true

If you really have to use arrays, then you can loop through all rows and find out the length that you must use:

int xcol = 0;
for(int i = 0; i < xrow; i++) {
    xcol = Math.max(xcol, x[i].length);
}

With this new xcol value, your code can proceed.

You may as well consider using flexible data structures such as array lists.

ernest_k
  • 44,416
  • 5
  • 53
  • 99