How can n arrays be read using a scanner in Java?

You can use a loop to read n array elements. Here is an example code using the Scanner class to read n array elements.

import java.util.Scanner;

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

        System.out.print("请输入数组的长度:");
        int n = scanner.nextInt();

        int[] arr = new int[n];

        System.out.println("请逐个输入数组元素:");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }

        System.out.println("输入的数组元素为:");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }

        scanner.close();
    }
}

In the code example above, first the length of the array n is read from the console using the Scanner class. Then an integer array arr of length n is created. Next, a loop is used to read each element of the array one by one and store it in the array. Finally, the elements of the array are output.

Please note that after reading all the array elements, we use scanner.close() to close the Scanner object. This is done to ensure proper resource release.

I hope this helps you!

bannerAds