2016-12-08 6 views
1

次のプログラムのために私はのような出力を期待しています:出力が期待どおりでないのはなぜですか? JavaのACMは

5 * 2^3 = 40

しかし、出力は次のようになります。まず

40 * 2^0 = 40

私はクラス「HandyInt」を構築:

/** 
* 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」上に構築、公開、実行コード、構築:

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()メソッドを呼び出すと、オブジェクトfactorおよびexpの内部が変更されたため、オブジェクトに変異が生じています。また、resultfactorと同じオブジェクトを指しています。

+0

ありがとう、私は "HandyInt"クラスで修正しました。 'add()'と 'sub()'メソッドで、私は新しいHandyIntを作成しました:\t \t 'HandyInt sub = new HandyInt(theInt); \t \t sub.theInt- = other.theInt; \t \t return sub; ' –

関連する問題