Jeremy
Jeremy

Reputation: 1675

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

Upvotes: 0

Views: 184

Answers (3)

nimi0112
nimi0112

Reputation: 2135

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;

Upvotes: 1

Vivek Bhojawala
Vivek Bhojawala

Reputation: 53

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

Upvotes: 1

Rehan Azher
Rehan Azher

Reputation: 1340

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

Upvotes: 1

Related Questions