1

In Java, how can I get the cumulative total of more than one primitive variables in the calling function. I would like to use another method to do the addition. But how do I do it in Java as it passes primitive types by value?

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();
}
  • Possible Duplicate: http://stackoverflow.com/questions/2832472/how-to-return-2-values-from-a-java-function – Johny T Koshy Aug 07 '12 at 03:01
  • 2
    Java does not have "Call By Reference" .. but this doesn't even attempt to show/simulate that. –  Aug 07 '12 at 03:04

2 Answers2

0

Unfortunately, Java does not support tuple assignment or references like most languages, making things unnecessarily difficult. I think your best bet is to pass in an array and then fill in the values from the array.

If you want to sum up all the values simultaneously, I'd look for some sort of vector class, though again, things are unnecessarily difficult due to the lack of operator overloading.

Antimony
  • 37,781
  • 10
  • 100
  • 107
0

Why don't you use a Car object as your total?

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());
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722