[英]Excluding the first and last element of array
I am trying to display array elements where all elements undergo a change, but the first and last element should remain the same.我试图显示所有元素都发生变化的数组元素,但第一个和最后一个元素应该保持不变。
Currently I have no idea on how to leave the first and last element alone.目前我不知道如何单独留下第一个和最后一个元素。
public static void main(String[] args) {
int num = 3;
int [] array = {2, 3, 2, 5, 3, 1};
int[] n = increaseValues(array, num);
System.out.println(Arrays.toString(n));
}//end of main
public static int[] increaseValues (int array[], int num){
int newArray[] = new int[array.length];
for(int i = 0; i < array.length; i++){
newArray[i] = array[i] * 3;
}
return newArray;
}//end of method
The current output is: 6, 9, 6, 15, 9, 3当前输出为:6, 9, 6, 15, 9, 3
Output should be: 2, 9, 6, 15, 9, 1输出应为:2, 9, 6, 15, 9, 1
How should would I implement this?我应该如何实现这一点?
You can change the function as this,你可以改变这个功能,
public static int[] increaseValues (int array[], int num){
for(int i = 1; i < array.length-1; i++){
array[i]= array[i] * 3;
}
return array;
}
So what happens is you will take the array
object then it will loop from 1st element to array.length-1
element and do the changes.所以会发生什么是您将获取array
对象,然后它将从第一个元素循环到array.length-1
元素并进行更改。
the output will look like this,输出将如下所示,
[2, 9, 6, 15, 9, 1]
public static int[] increaseValues(int array[], int num) {
int newArray[] = new int[array.length];
for (int i = 1; i < array.length - 1; i++) {
if (i == 0 || i == array.length - 1) {
newArray[i] = array[i];
} else {
newArray[i] = array[i] * 3;
}
array[i] = array[i] * 3;
}
return array;
}//end of method
output输出
[2, 9, 6, 15, 9, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.