boersencrack - 1 year ago 59

Java Question

I have a 2D-array to which I have to add a certain value, but only to one column of the 2D-array. One row of the 2D-array has to skipted and will stay the same as before.

I already have a code (see below), but that is just adding the value, not calculating it.

My code so far:

`double lowest = Double.parseDouble(excelMatrix[0][0]);`

int row = 0, column = 0;

List usedRow = new ArrayList();

for(int r = 0; r<excelMatrix.length-1; r++){

for(int c = 0; c<excelMatrix[r].length; c++){

double number = Double.parseDouble(excelMatrix[r][c]);

if(lowest > number) {

lowest = number;

row = r;

column = c;

}

}

}

usedRow.add(row);

for(int r = 0; r < excelMatrix.length; r++){

if( r != row)

excelMatrix[r][column] += lowest;

}

The initial matrix looks something like this:

`{1 , 2 , 3 , 4 , 5}`

{5 , 4 , 3 , 2 , 1}

{4 , 5 , 1 , 2 , 3}

{2 , 3 , 4 , 5 , 1}

{3 , 4 , 5 , 1 , 2}

and by adding 10 to column 3, except row 3, I would like to get:

`{1 , 2 , 3 , 14 , 5}`

{5 , 4 , 3 , 12 , 1}

{4 , 5 , 1 , 12 , 3}

{2 , 3 , 4 , 5 , 1}

{3 , 4 , 5 , 11 , 2}

But at the moment I am getting:

`{1 , 2 , 3 , 410 , 5}`

{5 , 4 , 3 , 210 , 1}

{4 , 5 , 1 , 210 , 3}

{2 , 3 , 4 , 5 , 1}

{3 , 4 , 5 , 110 , 2}

I hope the example makes my problem clear. Thank you!

Answer Source

Based on the output you are getting, it looks like the type of `excelMatrix`

is `String[][]`

, so when you are using the `+=`

operator you are concatenating a number to a String.

If you change your `excelMatrix`

array to `int[][]`

, you'll get the desired output.

If `excelMatrix`

must remain a `String[][]`

, you can still perform the addition by converting the `String`

to `int`

, performing addition and converting back to `String`

(though that would be less efficient) :

```
excelMatrix[r][column] = Integer.toString(Integer.parseInt(excelMatrix[r][column]) + value);
```