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;
    }
}

3 answers

  • answered 2018-04-17 05:22 nimi0112

    Instead of

     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;
    

  • answered 2018-04-17 05:22 Rehan Azher

    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;
    }
    

  • answered 2018-04-17 05:22 Vivek Bhojawala

    Following line is having problem

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

    in this your j loop is iterating to j < n and for last iteration you are trying to access j+1 so that index does not exist.

    either you can try in for loop

    j < tamaño-1