【问题标题】:Construction of a class in javajava中类的构造
【发布时间】:2017-01-28 09:16:45
【问题描述】:

我应该在创建一个类的时候进行这个练习,我上传了这个是教授的解决方案,总之和产品方法不太清楚什么地方和为什么使用“A”。

class Vettore {
    private int[] V = new int[6];
    public Vettore(int[] X) {
        if (X.length != 6)
            throw new BadDataException();
        for (int i = 0; i < 6; i++)
            if (X[i] < 0)
                throw new BadDataException();
            else
                V[i] = X[i];
    }
    public Vettore() {}
    public Vettore somma(Vettore X) {
        int[] A = new int[6];
        for (int i = 0; i < 6; i++)
            A[i] = V[i] + X.V[i];
        return new Vettore(A);
    }
    public Vettore prodotto(Vettore X) {
        int k = 0;
        for (int i = 0; i < 6; i++)
            k += V[i] * X.V[i];
        return k;
    }
    public int get(int i) {
        if (i < 0 || i > 5)
            throw new BadDataException();
        return V[i];
    }
    public String toString() {
        String t = "( ";
        for (int i = 0; i < 6; i++)
            t += V[i] + (i == 5 ? " " : ", ");
        return t + ")";
    }
    public boolean equals(Vettore X) {
        for (int i = 0; i < 6; i++)
            if (V[i] != X.V[i])
                return false;
        return true;
    }
}

【问题讨论】:

  • 您的prodotto 方法返回int,而其签名指定Vettore 返回类型!您可能应该详细说明您要达到的目标。

标签: java arrays class methods


【解决方案1】:

据我所知,假设somma 表示sumprodotto 表示product,则需要A,因为您必须存储V 和@987654327 的总和值@数组每个索引。如果您没有为此使用另一个array,例如,您将无法在somma 中添加适当的索引。这种方法代表 - 如我所见 - Adding the two arrays' appropriate elements

编辑: 另一件事。您确定返回类型匹配要返回的变量吗?我详细阐述了somma的使用,但没有注意prodotto的返回类型错误,正如cmets中所说的那样。

【讨论】:

    【解决方案2】:
    1. 您可能希望将 prodotto 方法定义更正为 -

      public Vettore prodotto(Vettore X) {
          int[] K = new int[6]; //  deault values are 0
          for (int i = 0; i < 6; i++)
              K[i] += V[i] * X.V[i];
          return new Vettore(K);
      }
      

    这将评估 Vettore 类的两个实例的数组字段 V 的乘积,命名为 X 输入参数和您将从中调用方法的当前实例。

    1. return new Vettore(K); 创建Vettore 类的新实例,其中 K 作为数组字段,同时执行构造函数逻辑如下 -

      public SumAndProductExercise(int[] X) {
          if (X.length != 6) { // length of the array is 6 or not
              throw new BadDataException();
          }
          for (int i = 0; i < 6; i++) {
              if (X[i] < 0) { // all the elements of array are >=0 or not
                  throw new BadDataException();
              } else {
                  V[i] = X[i]; // the field on the new instance
              }
          }
      }
      

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2018-02-28
      • 2018-06-13
      相关资源
      最近更新 更多