2

I am trying to create one array of objects of my class Percurso for another class Custos, but I don't know how to do this. Here is what is asking in the question:

Receives as parameter an array of path-type objects

My code :

Class Custos :

public class Custos {

    public String calcularViagem(Percurso [] p) {   
        return "";  
    }
}

Class Percurso :

private double kmPercorrida;
private double valorCombustivel;
private double valorPedagio;

public double getKmPercorrida() {
    return kmPercorrida;
}

public void setKmPercorrida(double kmPercorrida) {
    this.kmPercorrida = kmPercorrida;
}

public double getValorCombustivel() {
    return valorCombustivel;
}

public void setValorCombustivel(double valorCombustivel) {
    this.valorCombustivel = valorCombustivel;
}

public double getValorPedagio() {
    return valorPedagio;
}

public void setValorPedagio(double valorPedagio) {
    this.valorPedagio = valorPedagio;
}

public Percurso() {
    this(0,0,0);
}

public Percurso(double kmPercorrida, double valorCombustivel,
        double valorPedagio) {

    this.kmPercorrida = kmPercorrida;
    this.valorCombustivel = valorCombustivel;
    this.valorPedagio = valorPedagio;
}

How can I do this ? If someone can help, I will thanks.

PS: Before someone say that this post is similar to other questions about array, it's not,I looked for questions similar that could help and I didn't found any that really could help me.

Darwin von Corax
  • 5,201
  • 3
  • 17
  • 28
Falion
  • 247
  • 1
  • 11

1 Answers1

0

Creating an array of Percurso objects is the same as creating an array of any object. To create the array, you will need to include a line like this:

Percurso[] percursoArray = new Percurso[LENGTH]; //with your own array name and length

However, that just creates an array; it doesn't put anything in it. To put Percurso objects in the array (or, more accurately references to the objects), you need code like this.

percusoArray[0] = new Percurso(5, 2, 1);
percusoArray[1] = new Percurso(1, 1, 1); //etc

Or, if the array is long, you could create the objects in a for loop:

for (int i = 0; i < LENGTH; i++){
     percusoArray[i] = new Percurso(1,2,3); //with your own values 
}

Of course, a question remains-- where should you put this code? Is the array of Percurso an attribute of Custos? If so, you might create the array as a class variable of Custos and populate it in the constructor for Custos. If it's not an attribute of Custos, but rather just a parameter for one of Custos methods, you'll need this code in whichever part of your code calls calcularViagem(), whether that is another method in Custos, a method in another class, or from inside your main method.

s.py
  • 197
  • 10