简体   繁体   English

排除数组的第一个和最后一个元素

[英]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.

相关问题 数组的最后一个元素在迭代时首先打印 - last element of the array gets printed first on iteration 如何在java中获取数组中的第一个和最后一个元素? - How to get first and last element in an array in java? 将第一个数组元素与最后一个交换,第二个与倒数第二个交换,依此类推 - Swapping first array element with last, second with second last and so on 在特定位置乘以数组中的元素? (第一个元素与最后一个元素等) - Multiply elements in an array in specific positions? (the first element with the last element etc) 如何比较首个元素和最后一个元素以降序对数组进行排序 - How to sort an array in descending order comparing the first element and the last 对数组进行排序,以便第一个和最后一个元素形成一个“对” - sort an array, so that first and last element will form a “pair” 堆排序未对数组的最后一个和第一个元素进行排序 - Heap-Sort not sorting the last and first element of the array 数组的旋转意味着每个元素右移一个索引,数组的最后一个元素也移到第一位 - Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place 获取数组的最后一个元素 - Get last element of an array ArrayList查找第一个和最后一个元素 - ArrayList Find First and Last Element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM