【发布时间】:2022-11-16 08:52:03
【问题描述】:
我正在学习普林斯顿的计算机科学入门课程(我不是学生,只是自学)。我正在处理这个assignment。
Main 调用了两个方法:amplify 和 reverse,这两个方法都返回一个数组。 Amplify 将数组中的所有值乘以常数 alpha。 Reverse 返回一个数组,该数组以相反的顺序列出原始数组值,例如。 {1,2,3} -> {3,2,1}。
Amplify 工作正常,但是当我调用 reverse 时什么也没有发生,我得到一个错误指出:The Value Assigned Is Never Used
public class audiocollage {
// Returns a new array that rescales a[] by a factor of alpha.
public static double[] amplify(double[] a, double alpha) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * alpha;
}
return a;
}
// Returns a new array that is the reverse of a[].
public static double[] reverse(double[] a) {
double[] b = new double[a.length];
for (int i = a.length - 1, j = 0; i >= 0; i--, j++) {
b[j] = a[i];
}
return b;
}
// Creates an audio collage and plays it on standard audio.
public static void main(String[] args) {
double[] samples = StdAudio.read("cow.wav");
double alpha = 2.0;
samples = amplify(samples, alpha);
samples = reverse(samples);
}
}
【问题讨论】:
-
那是警告,不是错误。编译器只是指出,在将
reverse的返回值分配给samples后,samples中的值未被使用。你是什么意思“当我打电话给 reverse 时什么也没有发生”?你期望发生什么? -
你对
samples什么都不做(在从反向分配结果之后),所以 Java 编译器警告你,这个分配是不必要的(你可以只做reverse(samples);)。