【问题标题】:Passing parameters to a method and creating a deep copy将参数传递给方法并创建深层副本
【发布时间】:2017-03-11 10:55:21
【问题描述】:
public class ScoreCard {  strong text  
     private double[] scores;
/** 
 * @param val
 * @param low
 * @param high
 * @return low if val < low, 
 * high if val > high, 
 * val if val is between low and high
 */

private double constrain(double val, int low, int high) {
    if (val < low)
        return low;
    if (val > high)
        return high;
    else
        return val;
    }

/**
 * DEEP copy m into scores with each item contrained between 0 and 100.
 * use method {@link this#constrain(double, int, int)}.
 * For example, if s = {-15.2, 67.4, 126.8}, scores should become
 * {0, 67.4, 100}, AND scores should be a DEEP copy of s.
 * @param s (assume s is not null)
 */

public void setMarks(double[] s) {
     for(int i = 0; i < s.length; i++) {
        if (s[i] < 0 || s[i] > 100)
            constrain(s[i], 0, 100);
            this.scores[i] = s[i];
    }
}

我已经在这部分代码上停留了一段时间。正如 Javadoc 所述,我无法将“constrain”的参数调用为“setMarks”来设置 100 到 100 的分数。我也不认为我的代码正确地创建了深层副本正确地将“s”转换为“scores”。

我们将不胜感激任何朝着正确方向的推动。

【问题讨论】:

  • 你调用了 constrain(),但是你忽略了方法返回的约束值。

标签: java copy parameter-passing


【解决方案1】:

问题是您只是将s 的值分配给scores,而没有考虑constraints 的结果。下面的代码应该可以做到。

public void setMarks(double[] s) {
     for(int i = 0; i < s.length; i++) {
        if (s[i] < 0 || s[i] > 100)
            this.scores[i] = constrain(s[i], 0, 100); // <- this solves!
        else
            this.scores[i] = s[i];
    }
}

作为替代方案,更简单、更干净:

private double constrain(double val, int low, int high) {
    if (val < low)
        return low;
    if (val > high)
        return high;
    return val; // <- notice here
}

public void setMarks(double[] s) {
     for(int i = 0; i < s.length; i++) {
           this.scores[i] =  constrain(s[i], 0, 100); // <- notice here
    }
}

【讨论】:

  • if 甚至没有必要。它是由方法本身完成的。
  • 我现在明白了。所以我试图传递数组而没有先正确地通过“约束”类?感谢您的帮助
  • 不,您正确地将数组传递给 setMarks 方法,但您没有使用约束方法正确设置分数数组的值(它不是一个类)。
猜你喜欢
  • 2012-05-16
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多