2016-12-08 1 views
1

:출력이 예상과 다른 이유는 무엇입니까? 자바 ACM 나는대로 출력을 기대하고 다음 프로그램에 대한

5 * 2^3 = 40

그러나 출력은 다음과 같습니다

40 * 2^0 = 40

우선

/** 
* An integer that provides arithmetic operations for great glory. 
*/ 
public class HandyInt { 

/** The integer represented by an instance of this class. */ 
private int theInt; 

/** 
* Constructs a new handy integer representing the given int. 
* 
* @param theInt 
*   the integer to be represented by this instance. 
*/ 
public HandyInt(int theInt) { 
    this.theInt = theInt; 
} 

/** 
* Constructs a new handy integer representing the integer represented by 
* the given handy integer. 
* 
* @param handyInt 
*   the handy integer to intialize the new object with. 
*/ 
public HandyInt(HandyInt handyInt) { 
    this.theInt = handyInt.theInt; 
} 

/** 
* Returns the integer represented by this instance. 
* 
* @return the represented integer. 
*/ 
public int getInt() { 
    return theInt; 
} 

/** 
* Returns a handy integer that represents the sum of this and the other 
* handy integer. 
* 
* @param other 
*   the handy integer to add. 
* @return sum of the two handy integers. 
*/ 
public HandyInt add(HandyInt other) { 
    theInt += other.theInt; 
    return this; 
} 

/** 
* Returns a handy integer that represents the result of subtracting the 
* other integer from this one. 
* 
* @param other 
*   the handy integer to subtract from this one. 
* @return difference of the two handy integers. 
*/ 
public HandyInt sub(HandyInt other) { 
    theInt -= other.theInt; 
    return this; 
} 

@Override 
public String toString() { 
    return Integer.toString(theInt); 
} 
} 

을 그리고 난, 공공 실행 코드를 빌드 할 때 내 수업 "HandyInt"구축이 : I 클래스 "HandyInt"를 구축

import acm.program.ConsoleProgram; 

public class ComplexMathSolver extends ConsoleProgram { 
@Override 
public void run() { 
    HandyInt factor = new HandyInt(5); 
    HandyInt exp = new HandyInt(3); 

    HandyInt result = multiplyWithPowerOfTwo(factor, exp); 

    println(factor + " * 2^" + exp + " = " + result); 
} 

/** 
* Returns the result of multiplying {@code factor} with 2 to the power of 
* {@code exp}. 
* 
* @param factor 
*   the handy integer to multiply with the power. 
* @param exp 
*   the exponent of the power. 
* @return the result of the multiplication. 
*/ 
private HandyInt multiplyWithPowerOfTwo(HandyInt factor, HandyInt exp) { 
    HandyInt one = new HandyInt(1); 

    while (exp.getInt() > 0) { 
     factor = factor.add(factor); 
     exp = exp.sub(one); 
    } 

    return factor; 
} 
} 

출력을 수정하려면 "HandyInt"클래스에 어떤 문제가 있습니까? 감사합니다.

+1

개체에 돌연변이가 발생했습니다. – GurV

답변

1

multiplyWithPowerOfTwo() 메서드를 호출 할 때 개체의 내부가 factorexp으로 변경 되었기 때문에 개체가 변경되었습니다. 또한 resultfactor과 동일한 개체를 가리 킵니다.

+0

감사합니다. "HandyInt"클래스에서 수정했습니다. 'add()'와'sub()'메소드에서 새로운 HandyInt를 만들었습니다 : \t \t'HandyInt sub = new HandyInt (theInt); \t \t sub.theInt - = other.theInt; \t \t return sub; –

관련 문제