gpt4 book ai didi

java - 将参数传递给方法并创建深拷贝

转载 作者:行者123 更新时间:2023-11-30 10:32:19 24 4
gpt4 key购买 nike

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”以设置 < 0 到 0 和 scores > 100 到 100 的分数。我也不认为我的代码正确地创建了深拷贝将“s”正确地转换为“scores”。

任何朝着正确方向的插入将不胜感激。

最佳答案

问题是您只是将 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
}
}

关于java - 将参数传递给方法并创建深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42734322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com