在Java中,你可以通过以下几种方法输入一个静态数组:
1. 使用`Scanner`类从键盘输入数组元素:
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 input array is:");
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
scanner.close();
}
}
2. 使用命令行参数输入数组元素:
public class InputArray {
public static void main(String[] args) {
int size = Integer.parseInt(args);
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = Integer.parseInt(args[i + 1]);
}
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
}
}
3. 使用静态初始化直接赋值数组元素:
public class StaticArrayExample {
private static int[] array = {1, 2, 3, 4, 5};
public static void main(String[] args) {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
4. 使用静态数组声明和赋值:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
以上是几种在Java中输入静态数组的方法。请选择适合你需求的方法进行操作