如何在 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]

更新於:2020 年 2 月 19 日

超過 14 千次瀏覽

開啟你的職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.