【问题标题】:Java ADT calling variablesJava ADT 调用变量
【发布时间】:2015-09-22 01:48:26
【问题描述】:

我是 Java 新手,我正在尝试创建 ADT。我的 ADT 涉及通过输入分子和分母来创建和处理分数。我希望我的一种方法将两个分数加在一起并根据两个总和的 gcd 返回一个简化的分数。我遇到的问题是实例化两个分数(分子和分母)的分量。该方法应占其他部分,表示为public Rational add(Rational other)。我分配的第一个变量是

int d1 = this.denominator;
int d2 = other.denominator;

但这似乎不起作用。以下是目前为止的方法:

public Rational add(Rational other){
  int d1 = this.denominator;
  int d2 = other.denominator;
  int dtotal = d1*d2;
  int n1 = this.numerator*d2;
  int n2 = other.numerator*d1;
  int ntotal = n1+n2;
  if(ntotal>dtotal){
    for(int i=1; i<=ntotal; i++){
      if(ntotal%i==0 && dtotal%i==0){
        gcd=i;
      }
    }
  }else if(dtotal>ntotal){
    for(int i=1;i<=dtotal;i++){
      if(dtotal%i==0 && ntotal%i==0){
        gcd=i;
      }
    }
  }else if(dtotal==ntotal){
    gcd=numerator;
  }
  numerator = ntotal/gcd;
  denominator = dtotal/gcd;
}

【问题讨论】:

  • 你能提供你写的代码sn-p吗?
  • 我已编辑问题以包含整个方法。我想我还应该提到,我已经在方法之外将分子、分母和 gcd 实例化为 int numerator;int denominator;int gcd;
  • 您是否在Rational 类中定义了成员变量denominatornumerator
  • 能否提供完整的课程。因为添加这些成员变量后,我没有收到任何编译错误。
  • 到目前为止,我已经添加了整个课程

标签: java adt instantiation


【解决方案1】:

您需要使用所需的方法在类之外定义您的接口。这是示例,请根据您的需要进行编辑。

interface Rational {    
  public int getNumerator();
  public int getDenominator();
  public Rational add(Rational other);
  public Rational multiply(Rational other);
  public int compareTo(Rational other);
}

现在你的类应该是这样定义的:

public class RationalC implements Rational {

  int gcd;
  int numerator;
  int denominator;


  @Override
  public int getNumerator() {
    return numerator;
  }

  @Override
  public int getDenominator() {
    return denominator;
  }

  @Override
  public Rational add(Rational other) {
    return null;
  }

  @Override
  public Rational multiply(Rational other) {
    return null;
  }

  @Override
  public int compareTo(Rational other) {
    return 0;
  }
}

添加您的addmultiply 方法定义。使用getNumerator()getDenominator() 来访问这些值,而不是直接访问它们。

【讨论】:

  • 哦,好吧,这让事情变得简单多了。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2015-12-08
  • 2020-06-19
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多