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;}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.