How to populate an array one value at a time by taking input from user in Java?

Java 8Object Oriented ProgrammingProgramming

To read data from user create a scanner class. Read the size of the array to be created from the user using nextInt() method. Create an array with the specified size. In the loop read the values from the user and store in the array created above.

Example

import java.util.Arrays;
import java.util.Scanner;

public class PopulatingAnArray {
   public static void main(String args[]) {
      System.out.println("Enter the required size of the array :: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      System.out.println("Enter the elements of the array one by one ");
      for(int i=0; i<size; i++) {
         myArray[i] = s.nextInt();
      }
      System.out.println("Contents of the array are: "+Arrays.toString(myArray));
   }
}

Output

Enter the required size of the array ::
5
Enter the elements of the array one by one
78
96
45
23
45
Contents of the array are: [78, 96, 45, 23, 45]
raja
Published on 09-Jan-2018 14:29:22
Advertisements