Java 用下一个元素替换数组的每个元素

Java 用下一个元素替换数组的每个元素

在Java中,数组是一个对象。它是一种非原始数据类型,可以存储相同数据类型的值。

根据问题的陈述,我们需要用下一个元素替换数组的每个元素,并且可以将最后一个元素替换为第一个元素。

让我们开始吧!

为了给您展示一些实例−

实例-1

Suppose the original array is {2, 3, 1, 4, 6}
After updating the array with its next element: {3, 1, 4, 6, 2}

实例-2

Suppose the original array is {12, 23, 11, 64}
After updating the array with its next element: {23, 11, 64, 12}

实例-3

Suppose the original array is {11, 22, 33, 44, 55}
After updating the array with its next element: {22, 33, 44, 55, 11}

步骤

步骤1 - 声明并初始化一个整数数组。

步骤2 - 将数组的第一个元素存储在临时变量中,以便将其替换为最后一个元素。

步骤3 - 将当前元素arr [i]替换为arr [i + 1]。继续进行,直到arr [lastIndex-1]。然后用temp值替换最后一个索引元素。

步骤4 - 打印数组的元素。

多种方法

我们提供了不同的解决方案。

  • 使用静态初始化数组元素

  • 使用用户定义的方法。

让我们逐个看一下程序及其输出。

方法1:使用静态初始化数组元素

在这种方法中,数组元素将在程序中进行初始化。然后,根据算法将数组元素替换为其下一个元素。

示例

import java.util.Arrays;
public class Main {
   //main method
   public static void main(String args[]) {
      //Declare and initialize the array elements
      int arr[] = {4,2,3,1};
      //get the length of the array
      int size=arr.length;
      //assign the first element of the array to int variable 'temp'
      int temp=arr[0];
      // Print the array elements
      System.out.println("Array elements are: "+Arrays.toString(arr));
      //replace the current element with next element
      for(int i=0; i < (arr.length-1); i++) {
         arr[i]=arr[i+1];
      }
      //replace the last element of the array with first element
      arr[size-1]=temp;
      //print the updated array
      System.out.println("Updated array: "+Arrays.toString(arr));
   }
}

输出

Array elements are: [4, 2, 3, 1]
Updated array: [2, 3, 1, 4]

方法2:使用用户定义的方法

在这种方法中,程序将初始化数组元素。然后通过将数组作为参数传递给用户定义的方法,在方法内根据算法将数组元素替换为其下一个元素。

示例

import java.util.Arrays;
public class Main {
   public static void main(String args[]){
      //Declare and initialize the array elements
      int arr[] = {4,2,3,1};
      replaceElement(arr);
   }

   public static void replaceElement(int[] arr) {
      //get the length of the array
      int size=arr.length;
      //assign the first element of the array to int variable 'temp'
      int temp=arr[0];
      // Print the array elements
      System.out.println("Array elements are: "+Arrays.toString(arr));
      //replace the current element with next element
      for(int i=0; i < (arr.length-1); i++) {
         arr[i]=arr[i+1];
      }
      //replace the last element of the array with first element
      arr[size-1]=temp;
      //print the updated array
      System.out.println("Updated array:"+Arrays.toString(arr));
   }
}

输出

Array elements are: [4, 2, 3, 1]
Updated array: [2, 3, 1, 4]

在这篇文章中,我们探讨了如何用Java将数组的每个元素替换为其下一个元素。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程