英文:
Multiply array elements by the array length: Java
问题
以下是翻译好的内容:
我正在尝试弄清楚为什么我的程序无法正常工作。我实际上正在尝试的是将数组的每个元素与该数组的长度相乘。例如,如果输入是一个数组:[2, 3, 1, 0],则输出将为:[8, 12, 4, 0]。
以下是我的程序:
public class Challenge {
public static int[] MultiplyByLength(int[] arr) {
for (int i = 0; i <= arr.length; i++){
return arr[i] * arr.length;
}
}
}
非常感谢您提前提供任何批评意见!
英文:
I'm trying to figure out why my program will not work. What I am essentially trying to do is multiply each element of an array, by the length of that particular array. For example, if the input is an array of
[2, 3, 1, 0]
it will yield this
[8, 12, 4, 0]
here is my program
public class Challenge {
public static int[] MultiplyByLength(int[] arr) {
for (int i = 0; i <= arr.length; i++){
return arr[i] * arr.length;
}
}
}
any criticism is appreciated in advance!
答案1
得分: 0
设置数值并在循环结束后返回。按照惯例,方法名以小写字母开头。而且你有一个数组索引错误。修复所有这些可能会看起来像这样,
public static int[] multiplyByLength(int[] arr) {
for (int i = 0; i < arr.length; i++){
arr[i] *= arr.length;
}
return arr;
}
英文:
Set the values and return after the loop. Method names, by convention, start with a lowercase letter. And you have an array indexing error. Fixing all of that might look something like,
public static int[] multiplyByLength(int[] arr) {
for (int i = 0; i < arr.length; i++){
arr[i] *= arr.length;
}
return arr;
}
答案2
得分: 0
为了避免类似这样的错误,您可以使用Java流
import java.util.Arrays;
public class Challenge {
public static int[] MultiplyByLength(int[] arr) {
return Arrays.stream(arr).map(i -> i * arr.length).toArray();
}
}
英文:
To avoid mistakes like this you can use java streams
import java.util.Arrays;
public class Challenge {
public static int[] MultiplyByLength(int[] arr) {
return Arrays.stream(arr).map(i -> i * arr.length).toArray();
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论