[英]How to get use input through ArrayList in java
For example if i typed 5 then arraylist should take five input 5 3 2 3 5 3例如,如果我输入 5 那么 arraylist 应该有五个输入 5 3 2 3 5 3
import java.util.Scanner*;
import java.io.*;
class Character {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
// initializing ArrayList
int n=sc.nextInt();
ArrayList<Integer> arr = new ArrayList<Integer>(n);
for (int i=1; i<=n; i++)
arr.add(i);
System.out.println(arr);
for (int i=0; i<arr.size(); i++)
System.out.print(arr.get(i)+" ");
}
}
This code is taking input from use input like if i types 5 then then it will take five input form 1 to five ie 1 2 3 4 5这段代码从使用输入中获取输入,就像我输入 5 那么它将采用五个输入形式 1 到 5,即 1 2 3 4 5
You should use sc.nextInt()
to get the input and add to the list arr.add(sc.nextInt());
您应该使用
sc.nextInt()
获取输入并添加到列表arr.add(sc.nextInt());
List<Integer> arr = new ArrayList<>();
for (int i=1; i<=n; i++) {
arr.add(sc.nextInt());
}
You need to ask the user for input inside your loop:您需要在循环中询问用户输入:
for (int i=1; i<=n; i++)
{
int j = sc.nextInt();
arr.add(j);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.