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

更新于:19-2 月 -2020

14K+ 次浏览

开启你的事业

完成课程,获得认证

开始
广告
© . All rights reserved.