如何动态声明 Java 数组。


要动态声明数组大小,请使用 Scanner 类从用户读取所需的整数值,并使用给定值创建一个数组

示例

import java.util.Arrays;
import java.util.Scanner;

public class PopulatingAnArray {
   public static void main(String args[]) {
      System.out.println("Enter the required size of the array :: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      System.out.println("Enter the elements of the array one by one ");
     
      for(int i = 0; i<size; i++) {
         myArray[i] = s.nextInt();
     }
     System.out.println("Contents of the array are: "+Arrays.toString(myArray));
   }
}

输出

Enter the required size of the array ::
5
Enter the elements of the array one by one
78
96
45
23
45
Contents of the array are: [78, 96, 45, 23, 45]

更新于: 2020 年 2 月 19 日

2K+ 次浏览

开启你的职业生涯

完成课程以获得认证

开始学习
广告
© . All rights reserved.