Java程式:用陣列的下一個元素替換每個元素
根據題目要求,我們必須編寫一個Java程式,用陣列的下一個元素替換陣列的每個元素。在Java中,陣列是一個物件。它是一種非基本資料型別,用於儲存相似資料型別的值。
在討論給定問題的解決方案之前,讓我們用一個例子來理解問題陳述:
示例場景
Input: arr[] = {12, 23, 11, 64} Output: updated array = {23, 11, 64, 12}
演算法
按照以下步驟用陣列的下一個元素替換陣列的每個元素:
- 步驟1 - 宣告並初始化一個整數陣列。
- 步驟2 - 將陣列的第一個元素儲存在一個臨時變數中,以便用最後一個元素替換它。
- 步驟3 - 用arr[i+1]替換當前元素arr[i]。一直繼續到arr[lastIndex-1]。並用臨時值替換最後一個索引元素。
- 步驟4 - 列印陣列的元素。
使用for迴圈
Java中的for迴圈是一種控制結構,允許你重複執行一段程式碼特定次數。在這裡,我們使用它來迭代給定陣列的每個元素,並用下一個元素替換當前元素。
示例
在這個Java程式中,我們使用for迴圈用陣列的下一個元素替換陣列的每個元素。
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]
使用arraycopy()方法
在這種方法中,我們使用arraycopy()方法將元素從原始陣列複製到新陣列,從第二個元素(即索引1)開始,並將它們放置在新陣列的開頭(即索引0)。
arraycopy()方法屬於System類的java.lang包。此方法將元素從源陣列(從指定位置開始)複製到目標陣列的指定位置。
示例
讓我們看看實際演示:
import java.util.Arrays; public class Main { public static void main(String[] args) { // given array int arr[] = {4, 2, 3, 1, 5}; // Print the array elements System.out.println("Array elements are: " + Arrays.toString(arr)); // new array int newArr[] = new int[arr.length]; // assign the first element of the array to a temp variable int temp = arr[0]; // replacing current element with next element System.arraycopy(arr, 1, newArr, 0, arr.length - 1); // replace the last element of the array with first element newArr[newArr.length - 1] = temp; // updated array System.out.print("Updated array: "); for (int j : newArr) { System.out.print(j + " "); } } }
執行後,你將得到以下輸出:
Array elements are: [4, 2, 3, 1, 5] Updated array: 2 3 1 5 4
廣告