2012-08-07 1 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

+2

자바는 "참조에 의해 호출을"이 없습니다 ..하지만이 표시/시뮬레이션하려고하지 않습니다. –

답변

0

불행히도 Java는 튜플 할당 또는 대부분의 언어와 같은 참조를 지원하지 않으므로 불필요하게 어려운 작업입니다. 최선의 방법은 배열을 전달한 다음 배열의 값을 채우는 것입니다.

모든 값을 동시에 요약하려면 일종의 벡터 클래스를 찾으십시오.하지만 연산자 오버로딩이 부족하여 불필요하게 어려운 점도 있습니다.

+0

왜 이것을 다운 그레이드 했습니까? 내가 자바를 비판했기 때문에? – Antimony

+0

감사의 안티몬. 나는 w/array를 시도해 보았다. –

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