Java Array Input: Reading Values with Scanner

In Java, you can use the Scanner class to obtain array values input from the console. Below is an example code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();
        
        int[] arr = new int[size];
        
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }
        
        System.out.println("The entered array is:");
        for (int i = 0; i < size; i++) {
            System.out.print(arr[i] + " ");
        }
        
        scanner.close();
    }
}

In this example, the user is asked to input the size and elements of an array, and the input array values are then printed out in the end.

bannerAds