2013-10-04 2 views
0

클래스를 찾기위한 코드가 있는데 대부분 이해하지만이 방법에 대해 혼란스러워합니다. 주어진 코드를 사용하면 마지막으로 넣은 값이 totalOfItems와 totalGiven이 0.0 이었기 때문에 리턴 변경이 항상 0이되지는 않을 것입니다. 나는 그것을 실행할 때 그것은 일어나지 않을 것이지만 나는 이유를 이해하고 싶다고 들었다. 누구든지 나를 도울 수 있습니까?메서드가 (올바르게) 변수를 0으로 선언하지만 왜 그런지 이해하지 못합니까?

public SelfCheckout() { 
this.totalOfItems = 0.0; 
this.totalGiven = 0.0; 
} 

/** 
    * This method will scan the item. 
* @param amount The amount the items cost. 
*/ 

public void scanItem (double amount){ 
this.totalOfItems = this.totalOfItems + amount; 
} 

/** The method will add the items scanned and return the total due. 
* 
* @return getTotalDue The getTotalDue is the total amount of items scanned. 
*/ 
public double getTotalDue(){ 
    return this.totalOfItems; 
} 

/** The method will show the amount that is received from the consumer. 
* 
*/ 
public void receivePayment(double amount){ 
    this.totalGiven = this.totalGiven + amount; 
} 

/**The method will calculate the amount of change due. 
* 
*/ 
public double produceChange(){ 
    double change = this.totalGiven - this.totalOfItems; 
    this.totalGiven = 0.0; 
    this.totalOfItems = 0.0; 
    return change; 

답변

3

문은 순서대로 실행됩니다. totalGiventotalOfItems의 변경 사항은 계산 된 후에 change을 변경하지 않습니다. 이를 위해

+0

그렇습니다.하지만 컴파일러에게 변경 사항을 반환하도록 요청하기 전에 totalGiven 및 totalOfItems를 0으로 변경 했으므로 0을 반환하지 않겠습니까? – user2769212

+0

@ user2769212'change'는 두 변수의 함수가 아닙니다. 변수를 계산할 때 변수의 값으로부터 계산되는 상수입니다. –

+0

좋아, 이제 알았어. 변경은 이제 원래의 this.totalGiven과 동일한 자체 변수입니다. this.totalOfItems; 따라서 변경에 영향을 미치지 않고 this.totalGiven 및 this.totalOfItems를 재설정하는 것이 좋습니다. 권리? – user2769212

0

:

double change = this.totalGiven - this.totalOfItems; 
this.totalGiven = 0.0; 
this.totalOfItems = 0.0; 
return change; 

당신은 당신이 원래의 변수를 재설정 다음, change을 A (비 제로) 값을 할당하고, 그런 다음에야 change의 값을 반환합니다. 변수 값은 다른 변수에 복사 된 다음 다시 설정됩니다.

+0

나는 당신이 방금 말한 것을 이해하기를 바란다 .... 나는 첫 번째 줄에서 "double change = this.totalGiven - this.totalOfItems;"라고 말하는 것을 생각한다. "totalGiven"및 "totalOfItems"는 실제로 다른 totalGiven 및 totalOfItems를 나타냅니다. 나는 그 (것)들 또는 무언가를 개명 할 필요가 있었다는 것을 생각했다, 그러나 지금 그 sortof는 이해된다 ..... – user2769212

+0

계산서는 순서대로 단순히 실행한다. 정말 간단합니다. 'return change;는'change'가 이미 가지고있는 값을 반환합니다. –

0

내가 생각하는 가정은 receivePayment와 scanItem이 이미 호출되었으므로 필드 변수를 0이 아닌 숫자에 다시 할당한다는 것입니다. 그러면 변화가 주어집니다. 이미 다음 트랜잭션의 변수를 재설정 한 변경을 계산 한 후에 트랜잭션이 닫힙니다.