如何将循环中的值输入到数组列表中?

时间:2015-07-21 15:44:00

标签: java arrays

这是我的代码:

public static void main(String[] args) {
    System.out.println("Please enter the number of values you would like to enter: ");
    Scanner scan = new Scanner(System.in);
    int intNumberOfNumbers = scan.nextInt();

    for (int i = 0; i < intNumberOfNumbers; i++) {
        System.out.println("Please enter a value for index " + i + ":");
        int intValue = scan.nextInt();
    }
}

我要做的是创建一个扫描程序,询问他们想要输入多少值以及该值是什么,这就是它要求输入数量的次数。问题是在我问这个问题后如何将数字添加到数组列表中?

2 个答案:

答案 0 :(得分:1)

public static void main(String args[]){
   Scanner sc=new Scanner(System.in);
   int numOfInput=sc.nextInt();
   ArrayList<Integer> array=new ArrayList<Integer>();

   while(numOfInput-->0){
      array.add(sc.nextInt());       
   }
}

答案 1 :(得分:-2)

public static void main(String[] args) {
    System.out.println("Please enter the number of values you would like to enter: ");
    Scanner scan = new Scanner(System.in);
    int intNumberOfNumbers = scan.nextInt();
    ArrayList<Integer> myArray= new ArrayList<>();
    for (int i = 0; i < intNumberOfNumbers; i++) {
        System.out.println("Please enter a value for index " + i + ":");
        int intValue = scan.nextInt();
        myArray.add(intValue);
    }
}