How to input an array in Java?

In Java, the Scanner class can be used to input an array. Here 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("请输入数组的长度:");
        int length = scanner.nextInt();
        
        int[] array = new int[length];
        
        System.out.println("请输入数组的元素:");
        for (int i = 0; i < length; i++) {
            array[i] = scanner.nextInt();
        }
        
        System.out.println("输入的数组为:");
        for (int i = 0; i < length; i++) {
            System.out.print(array[i] + " ");
        }
        
        scanner.close();
    }
}

When running the code above, the program will prompt the user to input the length of the array and then prompt the user to input the value of each element. Finally, the program will print out the entire input array.

Please note that the code above uses the Scanner class to read user input, and requires importing the java.util.Scanner class at the beginning. Additionally, the scanner.close() method is used to close the Scanner object.

bannerAds