我正在尝试为另一个类Custos创建我的类Percurso的一个对象数组,但我不知道如何做到这一点。以下是问题中的问题:
作为参数接收路径类型对象数组
我的代码:
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;
}
我该怎么做?如果有人可以提供帮助,我会谢谢。
PS:在有人说这篇文章类似于关于数组的其他问题之前,我没有找到类似的问题可以提供帮助,而且我没有找到任何可以帮助我的问题。答案 0 :(得分:0)
创建Percurso
个对象的数组与creating an array of any object.相同。要创建数组,您需要包含如下所示的行:
Percurso[] percursoArray = new Percurso[LENGTH]; //with your own array name and length
然而,这只是创建一个数组;它没有任何东西。要将Percurso
个对象放入数组中(或者更准确地说是references to the objects),您需要这样的代码。
percusoArray[0] = new Percurso(5, 2, 1);
percusoArray[1] = new Percurso(1, 1, 1); //etc
或者,如果数组很长,您可以在for循环中创建对象:
for (int i = 0; i < LENGTH; i++){
percusoArray[i] = new Percurso(1,2,3); //with your own values
}
当然,问题仍然存在 - 你应该把这段代码放在哪里? Percurso
数组是Custos
的属性吗?如果是这样,您可以将数组创建为Custos
的类变量,并将其填充到Custos
的构造函数中。如果它不是Custos
的属性,而只是Custos
方法之一的参数,那么您在代码调用的任何部分{{1}都需要此代码},无论是calcularViagem()
中的另一种方法,另一种类中的方法,还是Custos
方法中的方法。