How to Take Array Input From User in Java?

In Java, you can take array input from the user using the Scanner class. Here's an example code snippet that shows how to take array input from the user in Java: 

 

import java.util.Scanner;

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

        // Ask the user for the length of the array
        System.out.print("Enter the length of the array: ");
        int length = scanner.nextInt();

        // Create an array with the specified length
        int[] array = new int[length];

        // Ask the user to enter the elements of the array
        System.out.printf("Enter %d elements:%n", length);
        for (int i = 0; i < length; i++) {
            System.out.printf("Element %d: ", i);
            array[i] = scanner.nextInt();
        }

        // Print the contents of the array
        System.out.print("Array contents: ");
        for (int i = 0; i < length; i++) {
            System.out.printf("%d ", array[i]);
        }
        System.out.println();
    }
}

In this code, we first create a Scanner object to read input from the user. We then ask the user for the length of the array and create an array with the specified length.

Next, we ask the user to enter the elements of the array using a for loop. Inside the loop, we prompt the user to enter the i-th element of the array and store it in the i-th index of the array.

Finally, we print the contents of the array using another for loop.

Submit Your Programming Assignment Details