【问题标题】:Printing location in memory when printing in the main method objects java在主要方法对象java中打印时在内存中打印位置
【发布时间】:2019-10-17 08:34:26
【问题描述】:

这是打印我在内存中的位置,为什么会发生这种情况以及如何解决它。

这是作业或考试的问题:

  1. 方法将这个 RationalNumber 的分子乘以 r 的分子,并将这个 RationalNumber 的分母乘以 r 的分母。以下哪项可用于替换 /* 缺少的代码 */ 以使 multiply() 方法按预期工作?

这些是解决方案,我需要选择:

num = num * r.num;
den = den * r.den;





this.num = this.num * r.num;
this.den = this.den * r.den;







num = num * r.getNum();
den = den * r.getDen();

我尝试了一切,但没有任何效果。

这是我的代码:

public class RationalNumber {
    private int num;
    private int den; // den != 0

    /** Constructs a RationalNumber object.
     *  @param n the numerator
     *  @param d the denominator
     *  Precondition: d != 0
     */
    public RationalNumber(int n, int d) {
        num = n;
        den = d;
    }

    /** Multiplies this RationalNumber by r.
     *  @param r a RationalNumber object
     *  Precondition: this.den() != 0
     */
    public void multiply(RationalNumber r) {
        /* missing code */
        num = num * r.num;
        den = den * r.den;

         //this.num = this.num * r.num;
        //this.den = this.den * r.den;

        //num = num * r.getNum();
       //den = den * r.getDen();
    }

    /** @return the numerator
     */
    public int getNum() {
        /* implementation not shown */
        return num;
    }

    /** @return the denominator
     */
    public int getDen() {
        /* implementation not shown */
        return den;
    }
    public static void main(String[] args){
        RationalNumber num = new RationalNumber(10, -1);
        System.out.println(num);


    }

    // Other methods not shown.
}

【问题讨论】:

    标签: java object methods printing main


    【解决方案1】:

    您需要重写 RationalNumber 类的 toString() 方法。

    System.out.println(num);
    

    如果我们没有指定类的任何特定属性或方法,上面的代码将打印所提供类的 toString() 方法的返回值。

    由于您的 RationalNumber 类没有覆盖 toString(),它会查找它的超类 toString()(Object 类)。

    你可以通过添加来解决这个问题

    @Override
    public String toString(){
        return num + "/" + den;
    }
    

    之后,您将需要 2 个 RationalNumber 对象。

    例如,在数学中,12 * 13 = 1⁄6

    在你的 main 方法中会有这样的东西

    public static void main(String[] args){
        RationalNumber rn1 = RationalNumber(1,2); //This represent 1/2
        RationalNUmber rn2 = RationalNumber(1,3); //This represent 1/3
        rn1.multiply(rn2); //This equals to 1/2 * 1/3, it multiply the num and den variable of rn1 object with rn2
        System.out.println(rn1); //This will invoke the toString() of rn1
    }
    

    【讨论】:

    • 谢谢,但现在它仍然只打印分子和分母,仍然不是上面给出的操作的结果
    • 这是因为你没有调用 multiply(RationalNumber r) 方法。
    • 我已经编辑了将调用乘法运算的答案。
    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2016-05-23
    • 1970-01-01
    • 2011-07-04
    相关资源
    最近更新 更多