2012-08-07 41 views
1

在Java中,如何在調用函數中獲得多個基本變量的累計總數。我想用另一種方法來進行添加。但是我怎樣在Java中做它,因爲它通過值來傳遞原始類型?Java - 調用方法的累計總數 - 按值調用

public void methodA(){ 
    int totalA = 0; 
    int totalB = 0; 
    Car aCar = getCar() ; //returns a car object with 2 int memebers a & b 

    methodB(aCar); 
    methodB(bCar); 
    methodB(cCar); 

    sysout(totalA); // should print the sum total of A's from aCar, bCar and cCar 
    sysout(totalB); // should print the sum total of b's from aCar, bCar and cCar   
} 

private methodB(aCar){ 
    totalA += aCar.getA(); 
    totalB += aCar.getB(); 
} 
+0

可能重複: http://stackoverflow.com/questions/2832472/how-to-return-2-values-from-a-java-function – 757071 2012-08-07 03:01:15

+2

Java沒有 「呼叫通過參考」 ..但這甚至不試圖顯示/模擬。 – 2012-08-07 03:04:00

回答

0

不幸的是,Java不支持元組賦值或像大多數語言一樣的引用,使事情變得不必要的困難。我認爲你最好的選擇是傳入一個數組,然後填入數組中的值。

如果你想同時總結所有的值,我會尋找某種向量類,但是由於缺少操作符重載,事情變得不必要地困難了。

+0

爲什麼這是低調的?因爲我批評了Java? – Antimony 2012-08-07 03:35:30

+0

感謝銻。我試過w /一個數組,它的工作。 – 2012-08-07 03:40:11

0

爲什麼不使用Car對象作爲總數?

public void methodA() { 
    Car total = new Car(); 
    Car aCar = getCar(); // etc 

    methodB(total, aCar); 
    methodB(total, bCar); 
    methodB(total, cCar); 

    sysout(total.getA()); // prints the sum total of A's from aCar, bCar and cCar 
    sysout(total.getB()); // prints the sum total of b's from aCar, bCar and cCar   
} 

private methodB(Car total, Car car){ 
    total.setA(total.getA() + car.getA()); 
    total.setB(total.getB() + car.getB()); 
}