Java Array List – Facing issue while taking values from user, but unknowingly program terminating

Tags: , ,



I am trying to take values from user in ArrayList, I can take input for the size of ArrayList, But, when I am trying to add elements, the program is being terminating. Here is my code

import java.io.*;
import java.util.*;
public class ArrayDemo{
public static void main(String...args)throws IOException
{
    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<Integer>(n);
        System.out.println("Enter the elements");
        for(int i=1;i<=n;i++) {
                a.add(b.read());
            }
        System.out.println(a);
            }catch(Exception e) {
        System.err.println("");
    }
}
}

Answer

You must use .readLine() also inside the loop:

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("");
        }
    }
}

Running result:

Enter the size of array:

3

Enter the elements

2
3
4
[2, 3, 4]

Process finished with exit code 0


Source: stackoverflow