# Sum elements in a matrix

I´m trying to sum all the elements of a single row in a matrix, I´m pretty sure this outputs an error message (Index out of range) since I´ve always made this mistake before in Python. I want to sum the elements in a loop too pls! (This matrix has a single column and a X ammount of rows. Sorry I didn´t clarify)

``````public class cls_ejercicio7_d {
private int tamaño;
private String[] lista_nombres;
private double[][] lista_kilometraje;

public cls_ejercicio7_d(int tamaño, String lista_nombres[], double lista_kilometraje[][]) {
this.lista_kilometraje = lista_kilometraje;
this.lista_nombres = lista_nombres;
this.tamaño = tamaño;
}

public double[][] resultados(int tamaño, String lista_nombres[], double lista_kilometraje[][]) {
double total;
double[][] lista_totales = new double[tamaño][1];
for (int i = 0; i < tamaño; i++) {
for (int j = 0; j < tamaño; j++) {
total = lista_kilometraje[i][j] + lista_kilometraje[i][j + 1];
lista_totales[i][j] = total;
}
}
return lista_totales;
}
}
``````

`````` double [][]lista_totales=new double[tamaño][1];
``````

do

`````` double [][]lista_totales=new double[tamaño][tamaño];
``````

and

`````` for (int j = 0; j < tamaño; j++) {
total+=lista_kilometraje[i][j];
}
lista_totales[i][1]=total;
``````

Error is from this line :

total=lista_kilometraje[i][j]+lista_kilometraje[i][j+1];

You are taking `j+1`. Assuming your matrix has 8 columns so for this one it will try to retrieve `j[8]` which is wrong as J only have index 7.

Also the size of `lista_totales = [tamaño][1]`

`lista_totales[i][j]` will also throw exception.

u may want to change to below :

``````public double [][] resultados(int tamaño,String lista_nombres[],double lista_kilometraje[][]){
double total;
double [][]lista_totales=new double[tamaño][1];
for (int i = 0; i < tamaño; i++) {
total = 0 ;
for (int j = 0; j < tamaño; j++) {
total+=lista_kilometraje[i][j];
}
lista_totales[i][1]=total;
}
return lista_totales;
}
``````

``````total = lista_kilometraje[i][j] + lista_kilometraje[i][j + 1];
``````j < tamaño-1