1

在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();
}
4

2 回答 2

0

不幸的是,Java 不像大多数语言那样支持元组分配或引用,这使事情变得不必要地困难。我认为您最好的选择是传入一个数组,然后填写数组中的值。

如果您想同时总结所有值,我会寻找某种矢量类,但由于缺少运算符重载,事情再次变得不必要地困难。

于 2012-08-07T02:59:56.663 回答
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());
}
于 2012-08-07T03:07:18.220 回答