如何在 java 中將陣列分成兩半?
使用 copyOfRange() 方法可以複製範圍內的陣列。此方法接受三個引數:要複製的陣列、範圍的開始和結束索引。
透過將從 0 到 length/2 範圍的陣列複製到一個數組,以及 length/2 到 length 範圍的陣列複製到另一個數組,來使用此方法分割一個數組。
示例
import java.util.Arrays;
import java.util.Scanner;
public class SplittingAnArray {
public static void main(String args[]) {
Scanner s =new Scanner(System.in);
System.out.println("Enter the required size of the array ::");
int size = s.nextInt();
int [] myArray = new int[size];
System.out.println("Enter elements of the array");
for(int i=0; i< size; i++) {
myArray[i] = s.nextInt();
}
System.out.println(Arrays.toString(myArray));
int[] myArray1 = Arrays.copyOfRange(myArray, 0, myArray.length/2);
int[] myArray2 = Arrays.copyOfRange(myArray, myArray.length/2, myArray.length);
System.out.println("First half of the array:: "+Arrays.toString(myArray1));
System.out.println("First second of the array:: "+Arrays.toString(myArray2));
}
}輸出
Enter the required size of the array :: 6 Enter elements of the array 45 63 78 96 42 19 [45, 63, 78, 96, 42, 19] First half of the array:: [45, 63, 78] First second of the array:: [96, 42, 19]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP