2016-03-19 48 views
1

我正在嘗試爲另一個類Custos創建我的類Percurso的一個對象數組,但我不知道如何執行此操作。這裏是被問的問題:接收Java中另一個類的對象數組的參數?

接收作爲參數路徑類型的數組對象

我的代碼:

類保管人

public class Custos { 

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

類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

創建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 
} 

當然,remains--一個問題應該在哪裏你把這個代碼? Percurso的數組是否屬於Custos?如果是這樣,您可以創建該數組作爲Custos的類變量,並將其填充到Custos的構造函數中。如果它不是Custos的屬性,而只是Custos方法之一的參數,則無論代碼的哪個部分調用calcularViagem(),您都需要使用此代碼,無論這是另一個類中的方法Custos中的另一種方法還是來自在您的main方法中。

+0

感謝您的幫助,我會盡力照你說的去做。 – Falion

相關問題