Java ArrayList-从用户获取值但在不知不觉中终止程序时遇到问题

时间:2018-07-29 10:08:19

标签: java arraylist collections

您好,我正在尝试从ArrayList中的用户获取值,我可以输入ArrayList的大小。但是,当我尝试在其中添加元素时,程序会自动终止。请在下面的代码中提供帮助?

NULL

1 个答案:

答案 0 :(得分:0)

您还必须在循环内使用.readLine()

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {

        try {
            BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the size of array:");

            int n = Integer.parseInt(b.readLine());

            ArrayList<Integer> a = new ArrayList<>(n);

            System.out.println("Enter the elements");

           for (int i = 1; i <= n; i++) {
               int value = Integer.parseInt(b.readLine());
               a.add(value);
           }

            System.out.println(a);

        } catch (Exception e) {
            System.err.println("");
        }
    }
}

运行结果:

Enter the size of array:

3

Enter the elements

2
3
4
[2, 3, 4]

Process finished with exit code 0