[英]Creating an array that starts at n and ends at 0
I'm having difficulty with the action below.我在执行以下操作时遇到困难。 I'm not sure how to reverse the array index starting at n and working down to 0. Can someone help me understand this?我不确定如何将数组索引从 n 开始反转为 0。有人可以帮助我理解这一点吗? I'm thinking of using a for loop, but I can't quite visualize how I would do that.我正在考虑使用 for 循环,但我无法想象我将如何做到这一点。
Thanks.谢谢。
• Add a method called public static int[] generateIntegerArray(int n) to the App class that returns a systematically generated integer array of length n that is reverse sorted starting at n-1 and ending at 0. For example a call generateIntegerArray(5) would result in this array: {4, 3, 2, 1, 0}. • 向 App 类添加一个名为 public static int[] generateIntegerArray(int n) 的方法,该方法返回一个系统生成的长度为 n 的整数数组,该数组从 n-1 开始到 0 结束进行反向排序。例如调用 generateIntegerArray(5 ) 将导致此数组:{4, 3, 2, 1, 0}。
public static int[] generateIntegerArray(int n){
int[] integerArray = new int[n];
return integerArray;
}
Try something like this:尝试这样的事情:
int[] integerArray = new int[n];
for(int i = 0; i < n; i++) {
integerArray[i] = n - i - 1;
}
return integerArray;
}
You should just fill that array with values from n-1 to 0您应该只用 n-1 到 0 的值填充该数组
for(int i=0; i<n; i++) {
integerArray[i] = n-i-1;
}
or或者
for(int i=n; i>0; i--) {
integerArray[n-i-1] = i;
}
public static int[] generateIntegerArray(int n){ public static int[] generateIntegerArray(int n){
int[] integerArray = new int[n];
for(int i = n - 1; i >= 0; --i){
integerArray[n - 1 - i] = i;
}
return integerArray;
} }
The for loop would run from n - 1 to 0 and the values would be put into array for 循环将从 n - 1 运行到 0,并将值放入数组中
public static int[] generateIntegerArray(int n){
int[] integerArray = new int[n];
for(int i = 0; i < n; i++) {
integerArray[i] = n - i - 1;
}
return integerArray;
}
for (int i = integerArray.length-1 ; i >=0; i--)
{
integerArray[i] = i;
}
That looks like(if lenght is 6, for example): 6,5,4,3,2,1,0 i - is number in loop, it changes in every loop(i--);看起来像(例如,如果长度为 6): 6,5,4,3,2,1,0 i - 是循环中的数字,它在每个循环中都会改变(i--); So, at the output it will looks like:所以,在输出中它看起来像:
integerArray[6]
integerArray[5]
integerArray[4]
integerArray[3]
integerArray[2]
integerArray[1]
integerArray[0]
If I understood you in right way)如果我以正确的方式理解你)
int[] integerArray = new int[]{1,2,3,4,5,6,7,8,9};
int[] reversedArray = new int[integerArray.length];
int j = 0;
for (int i = integerArray.length -1; i > 0; i--){
reversedArray[j++] = integerArray[i];
}
Hope you find this helpful..希望你觉得这有帮助..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.