How to Take Array Input in Java - The Coding Shala

Home >> Java Programs >> Take Array Input

 In this post, we will learn how to take an array input in Java.

How to Take Array Input in Java

Write a Java Program to take array input from the user. In this program, we are going to take only an integer array as input.

We are going to use the Scanner class to take integer inputs. The below are steps to take array input:

  1. Take the size of the array as input.
  2. Create the array of the above size.
  3. Using for loop take integer elements from the user as input.
  4. Print the array.

Java Program: 

import java.util.Scanner;

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array");
        int size = sc.nextInt();

        // create an array of given size
        int[] arr = new int[size];

        // take integer inputs using for loop
        System.out.println("Enter " + size + " elements");
        for (int i=0; i < size; i++) {
            arr[i] = sc.nextInt();
        }

        // print array
        System.out.println("The Array is: ");
        for (int i=0; i < size; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output: 

Enter the size of array
5
Enter 5 elements
1
2
3
4
5
The Array is: 
1 2 3 4 5 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

New Year Chaos Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala