The user has to give an index of a row where they want to insert it, like this:
original:
2.546 3.664 2.455
1.489 4.458 3.333
insert an index row: 1
[4.222, 2.888, 7.111]
row inserted:
2.546 3.664 2.455
4.222 2.888 7.111
1.489 4.458 3.333
here is the code:
public double[] getTheDataForRow( int len )
{
double [] num = new double [len];
return num;
}
public double[][] insertRow( double[][] m, int r, double[] data){
m = new double [data.length][3];
for(int row = 0; row<m.length; row++){
for(int col = 0; col<m[row].length;col++)
if(m[row][col] == r){
m[row][col] = data;
}
}
return m;
}
public void result(double[][] s){
for(int row=0; row<s.length; row++){
for(int col=0; col<s[0].length; c++)
out.printf( "%5.2f", s[row][col] );
out.println();
}
out.println();
}
I keep having an error and I honestly do not know how to fix it. I would appreciate some help.
You are clobbering your input array m
on the first line of your insertRow
. Instead, create a new array of one more element in size. Then copy everything before the insertion point from the input. Then insert the new row. Then copy everything after that row from the input (shifted back one against the current index). And, I would make the method static
. Like,
public static double[][] insertRow(double[][] m, int r, double[] data) {
double[][] out = new double[m.length + 1][];
for (int i = 0; i < r; i++) {
out[i] = m[i];
}
out[r] = data;
for (int i = r + 1; i < out.length; i++) {
out[i] = m[i - 1];
}
return out;
}
Then to test it,
public static void main(String[] args) {
double[][] arr = { { 2.546, 3.664, 2.455 }, { 1.489, 4.458, 3.333 } };
System.out.println(Arrays.deepToString(arr));
arr = insertRow(arr, 1, new double[] { 4.222, 2.888, 7.111 });
System.out.println(Arrays.deepToString(arr));
}
And I get (as expected)
[[2.546, 3.664, 2.455], [1.489, 4.458, 3.333]]
[[2.546, 3.664, 2.455], [4.222, 2.888, 7.111], [1.489, 4.458, 3.333]]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments