如何通过使用Java中的用户输入来一次填充一个值的数组?
要从用户读取数据,请创建一个扫描器类。使用nextInt()方法从用户读取要创建的数组的大小。创建具有指定大小的数组。在循环中,从用户读取值并将其存储在上面创建的数组中。
示例
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 高考祝福语 简短12字
15 庆祝论坛周年祝福语简短
16 母亲贺卡生日祝福语简短
17 祝福语献给老人的话简短
18 小孩想说的祝福语简短