Open In App

How to Take Array Input From User in Java?

Last Updated : 17 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Arrays in Java are an important data structure, and we can add elements to them by taking input from the user. There is no direct method to take input from the user, but we can use the Scanner Class or the BufferedReader class, or the InputStreamReader Class.

Different Ways to Take Array Input from User

1. Using Scanner Class to Take Array Input

Approach:

  • First, we create an object of the Scanner Class and import the java.util.Scanner package.
  • Then create a variable for taking the size of the array from the user, and show the message “Enter size of array
  • Then we use the hasNextInt() and nextInt() methods of the Scanner class to take integer input from the user through the console.
  • Then we print each element of the array using a loop.
  • Then we close the Scanner object when we have completed the program for best practice.

Example: Taking input from the user in a one-dimensional array using the Scanner class and loops.

Java
// Java program to take 1D array 
// input from the user
// using Scanner class and loops
import java.util.Scanner;

public class Geeks
{
  
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Take the array size from the user
        System.out.println("Enter the size of the array: ");
        int s = 0;
        if (sc.hasNextInt()) {
            s = sc.nextInt();
        }

        // Initialize the array's
        // size using user input
        int[] arr = new int[s];

        // Take user elements for the array
        System.out.println(
            "Enter the elements of the array: ");
        for (int i = 0; i < s; i++) {
            if (sc.hasNextInt()) {
                arr[i] = sc.nextInt();
            }
        }

        System.out.println(
            "The elements of the array are: ");
        for (int i = 0; i < s; i++) {
           
            System.out.print(arr[i] + " ");
        }
        sc.close();
    }
}

Output:

OutputArray

Explanation: In this example, first we use the Scanner class to accept user input and save the array size in the size variable. Then we make an array arr with the size s. Following that, we use a for loop to accept user input and save it in an array. Finally, we use another for loop to print the array’s elements.

2. Taking Input Two-dimensional Array Using Scanner Class

The Scanner class from java.util helps to take user input. We can use the Scanner class with loops to take input for individual array elements (to use this technique, we must know the length of the array).

In this example, we will understand how to take input for a two-dimensional array using the Scanner class and loops.

Approach:

  • First, we create an object of the Scanner Class and import the java.util.Scanner package.
  • Then create two variables for taking the row and column size of the array from the user, show the message to enter the row and column one by one.
  • Then we use the hasNextInt() and nextInt() methods of the Scanner class to take integer input from the user through the console with nested loop.
  • Then we print each element of the array using nested for loop.
  • Then close the Scanner object.

Example: Taking input of Two dimenstional array from the user.

Java
// Java program to take 2D array input from the user
// Using Scanner class and loops
import java.util.Scanner;

public class Geeks {
  
    public static void main(String[] args) {
      
        Scanner sc = new Scanner(System.in);

        // Prompt the user for the dimensions of the array
        System.out.print("Enter the number of rows: ");
        int r = sc.nextInt();
        System.out.print("Enter the number of columns: ");
        int c = sc.nextInt();

        // Create the 2D array
        int[][] arr = new int[r][c];

        // Prompt the user to enter values for the array
        System.out.println("Enter the elements of the array:");

        // Input loop to populate the array
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                System.out.print("Enter element at position [" + i + "][" + j + "]: ");
                arr[i][j] = sc.nextInt();
            }
        }

        System.out.println("The entered 2D array is:");
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                System.out.print(arr[i][j] + " ");
            }
            // Move to the next line for the next row
            System.out.println(); 
        }

        // Close the Scanner object
        sc.close();
    }
}

Output:

OutputArray2

Explanation: In this example, first we use the Scanner class to accept user input of the number of rows and columns to create a 2D array. Then, we use a for loop to accept user input and save it in the 2D array. Finally, we use another for loop to print the array’s elements.

3. Using BufferedReader and InputStreamReader Class

We can use the BufferedReader and InputStreamReader classes to read user input in Java and use the IOException class to handle exceptions in input.

In the below example, we use the BufferedReader object to read user input and manage the input classes that even with the wrong input type the error is not thrown.

Approach:

  • Initialize the important packages in the program mentioned in the below code such as BufferedRead, IOException and InputStremReader from java.io.
  • In the method where we use the BufferedReader and InputStreadReader throws the IOException
  • Then initialize the object of InputStreamReader and pass the System.in in the constructor.
  • Then create the object of BufferedReader and pass the InputStreamReader object in the constructor.
  • Take the size of the array from the user. The BufferedReader read the String and we use the ParseInt() method so if the user enter other than the integer number then it will throw exception so handle it using try catch.
  • Then take the input of the array elements from the user and print it using the loop
  • In the end close the BufferedReader object.

Example: Taking input of an array from user using BufferedReader and InputStreamReader.

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Geeks
{
    public static void main(String[] args) throws IOException 
    {
        // Initializing the object InputStreamReade 
         
        InputStreamReader in = new InputStreamReader(System.in);
        
        // Initializing the object of BufferedReader 
        BufferedReader br = new BufferedReader(in);

        // Take the array size from the user
        System.out.println("Enter the size of the array: ");
        int s = 0;
        try {
            s = Integer.parseInt(br.readLine());
        } catch (NumberFormatException e) {
            System.out.println("Invalid input for array size. Please enter a valid integer.");
            return;
        }

        // Initialize the array's
        // size using user input
        int[] arr = new int[s];

        // Take user elements for the array
        System.out.println("Enter the elements of the array: ");
        for (int i = 0; i < s; i++) {
            try {
                arr[i] = Integer.parseInt(br.readLine());
            } catch (NumberFormatException e) {
                System.out.println("Invalid input for array element. Please enter a valid integer.");
                return;
            }
        }

        System.out.println("The elements of the array are: ");
        for (int i = 0; i < s; i++) {
          
            System.out.print(arr[i] + " ");
        }

        // Close the BufferedReader
        br.close();
    }
}


Output:

BuffereReaderInputArray

Explanation: In this example, we use BufferedReader and InputStreamReader classes to capture user input and construct an array based on the specified size. We make an array arr with the size s. We handle potential input errors with try-catch blocks. Then, we initialize and populate an array with user input, and use a loop to print its elements.



Next Article
Practice Tags :

Similar Reads