How can Java pass input values to an array?

Here is the method in Java for taking input values and assigning them to an array:

  1. To get user input values, use the Scanner class. First, import the java.util.Scanner class.
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.println(array[i]);
        }

        // 关闭Scanner
        scanner.close();
    }
}

In the example code above, the Scanner class is first used to get the length of the array input by the user, then an integer array is created based on the array length. Next, a loop structure is used to get the array values input by the user and assign them to each element in the array. Finally, another loop structure is used to print the value of each element in the array.

  1. Use command-line arguments to retrieve input values. When running a Java program, you can pass input values through parameters in the command line.
public class Main {
    public static void main(String[] args) {
        // 获取数组的长度
        int length = Integer.parseInt(args[0]);

        // 创建数组
        int[] array = new int[length];

        // 获取数组的值
        for (int i = 0; i < length; i++) {
            array[i] = Integer.parseInt(args[i + 1]);
        }

        // 打印数组的值
        for (int i = 0; i < length; i++) {
            System.out.println(array[i]);
        }
    }
}

In the example code above, the program retrieves the command-line arguments passed through the args array. Index args[0] represents the length of the array, and args[1] onwards represents the values of the array. By using a loop structure, the program passes the arguments to each element in the array and prints out the value of each element.

Both methods can be used to input values into an array, the specific method to use depends on the actual needs and usage scenarios.

bannerAds