在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 :(得分:0)
不幸的是,Java不支持元组赋值或大多数语言的引用,这使得事情变得不必要。我认为你最好的选择是传入一个数组,然后填充数组中的值。
如果你想同时总结所有的值,我会寻找某种类型的向量类,但是由于缺少运算符重载,事情也是不必要的。
答案 1 :(得分: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());
}