我有一个简单的for循环,要求用户输入10次整数。如何将这些输入添加到数组而不必创建10个单独的变量?
Scanner scan = new Scanner(System.in);
for (int i = 1; i<= 10; i++) {
System.out.println("Please enter an Integer:");
scan.nextInt();
}
}
示例输入:10,1,3,25,33,26,12,0,7,18
所需输出:myArray = [10,1,3,25,33,26,12,0,7,18]
答案 0 :(得分:0)
这样的事可能吗?
Scanner scan = new Scanner(System.in);
int [] input_nums = new int [10];
for (int i = 1; i<= 10; i++) {
System.out.println("Please enter an Integer:");
int a = scan.nextInt();
input_nums[i] = a;
}
}
答案 1 :(得分:0)
使用此: 这假设您需要输入10个数字
public void test5(){
Scanner scan = new Scanner(System.in);
int[] arr = new int[10];
for (int i = 0; i< 10; i++) {
System.out.println("Please enter an Integer:");
arr[i]=scan.nextInt();
}
scan.close();
//To check array output
for(int a:arr){
System.out.println(a);
}
}
如果你想让它更具动态性(预先不知道数组大小),你可以试试这个:
public void test6(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter Integers(in a single line separated by space):");
int[] intArr = null;
if(scan.hasNext()){
String line = scan.nextLine();
intArr = Arrays.stream(line.split("\\s+")).mapToInt(Integer::parseInt).toArray();
}
scan.close();
for(int a: intArr) {
System.out.println(a);
}
}
答案 2 :(得分:0)
使用ArrayList:
Scanner scan = new Scanner(System.in);
ArrayList array = new ArrayList();
for (int i = 1; i<= 10; i++) {
System.out.println("Please enter an Integer:");
int number = scan.nextInt();
array.add(number);
}