如何动态声明具有数组大小的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]
热门推荐
10 节日祝福语幽默简短的
11 高温祝福语短语大全简短
12 高考送考祝福语简短
13 女儿结婚账单祝福语简短
14 发小结婚简短祝福语
15 新年祝福语长篇文案简短
16 送去考试祝福语简短英文
17 红颜生日祝福语简短独特
18 家长祝福语大全简短内容