Open In App

How to Take Array Input From User in Java

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

There is no direct method to take array input in Java from the user. In this article, we will discuss two methods to take array input in Java. But first, let’s briefly discuss arrays in Java and how they differ from other programming languages.

Array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Some important points about Java arrays are:

  • Arrays are dynamically allocated.
  • Arrays are stored in contiguous memory [consecutive memory locations].
  • Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered, and each has an index beginning with 0.

Read More: Arrays in Java

How to Take Array Input in Java?

In Java, there are two simple ways to take array input from the user. You may utilize loops and the “Scanner class” or “BufferedReader and InputStreamReader class” to accept an array input from the user.

Let’s cover both these methods in detail with examples.

Using Scanner Class and Loops

The Scanner class is part of the ‘java.util‘ package and is used to take input from the user. 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).

Below is the implementation of using Scanner class and loops to take array input in Java:

Example 1: One-dimensional array input in Java

Taking input in a one-dimensional array in Java using Scanner class and loops.

Java




// Java program that accepts
// array input from the user.
import java.util.Scanner;
 
public class GFG {
    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 arr_size = 0;
        if (sc.hasNextInt()) {
            arr_size = sc.nextInt();
        }
 
        // Initialize the array's
        // size using user input
        int[] arr = new int[arr_size];
 
        // Take user elements for the array
        System.out.println(
            "Enter the elements of the array: ");
        for (int i = 0; i < arr_size; i++) {
            if (sc.hasNextInt()) {
                arr[i] = sc.nextInt();
            }
        }
 
        System.out.println(
            "The elements of the array are: ");
        for (int i = 0; i < arr_size; i++) {
            // prints the elements of an array
            System.out.print(arr[i] + " ");
        }
        sc.close();
    }
}


Output:

1d-array-input-in-java

Explanation of the above Program:

In this example, we first utilize 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 ‘arr_size’. 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.

Example 2: Two-dimensional Array Input in Java

Taking input in a two-dimensional array in Java using Scanner class and loops.

Java




import java.util.Scanner;
 
public class TwoDArrayInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        // Prompt the user for the dimensions of the array
        System.out.print("Enter the number of rows: ");
        int rows = scanner.nextInt();
        System.out.print("Enter the number of columns: ");
        int columns = scanner.nextInt();
 
        // Create the 2D array
        int[][] array = new int[rows][columns];
 
        // 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 < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print("Enter element at position [" + i + "][" + j + "]: ");
                array[i][j] = scanner.nextInt();
            }
        }
 
        // Output the array
        System.out.println("The entered 2D array is:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println(); // Move to the next line for the next row
        }
 
        // Close the Scanner object
        scanner.close();
    }
}


Output:

2d-array-input-java

Explanation of the above Program:

In this example, we first utilize the Scanner class to accept user input of the number of rows and columns to create a 2D array. Following that, 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.

Using BufferedReader and InputStreamReader Class

We can use the BufferedReader object to read user input in Java and use the IOException Class to handle exceptions in input.

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

Example:

Java




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class GFG {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
        // Take the array size from the user
        System.out.println("Enter the size of the array: ");
        int arr_size = 0;
        try {
            arr_size = 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[arr_size];
 
        // Take user elements for the array
        System.out.println("Enter the elements of the array: ");
        for (int i = 0; i < arr_size; 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 < arr_size; i++) {
            // prints the elements of an array
            System.out.print(arr[i] + " ");
        }
 
        // Close the BufferedReader
        br.close();
    }
}


Output:

bufferedreader-array-input-in-java

Explanation of the above Program:

In this example, we utilize 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 ‘arr_size’.

We handle potential input errors gracefully with try-catch blocks. Following that, we initialize and populate an array with user input, and use a loop to print its elements.

Conclusion

In conclusion, array input is important for building user-friendly Java applications. While Java lacks a direct array input method, we’ve explored two effective approaches in this tutorial.

We’ve covered 1D and 2D array input cases with easy examples and exception-handling techniques. By mastering these techniques, you’ll enhance your Java skills and create more resilient applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads