A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Create an ArrayList and enter run time elements in array using Scanner class.

Programming steps:

1. Create an ArrayList: 



  ArrayList<String>   mylist = new ArrayList<>();

2. Use Scanner class:

Scanner sc = new Scanner(System.in);


3. enter run time elements in arraylist:

      int i, n;
      n=sc.nextInt();
      for( i=1; i<=n; i++)
      {
            Scanner sc1 = new Scanner(System.in);
            System.out.println("Enter username: ");
            String name=sc1.nextLine();
            mylist.add(name);
      }

Complete Program code:


import java.util.ArrayList;

import java.util.Scanner;
public class A
{
    public static void main(String a[])
    {
        ArrayList<String>   mylist = new ArrayList<>();
        System.out.println("Enter number of element in arraylist: ");
        Scanner sc = new Scanner(System.in);
        int i, n;
        n=sc.nextInt();
        for( i=1; i<=n; i++)
        {
            Scanner sc1 = new Scanner(System.in);
            System.out.println("Enter username: ");
            String name=sc1.nextLine();
            mylist.add(name);
        }
        System.out.println("List is: "+mylist);
    }
}


LEARN TUTORIALS

.

.