1. 使用`Scanner`类:
```java
import java.util.Scanner;
public class ArrayInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] myArray = new int;
for (int i = 0; i < myArray.length; i++) {
System.out.print("Enter value for index " + i + ": ");
myArray[i] = input.nextInt();
}
input.close();
// 可以在这里添加代码来使用数组
}
}
2. 使用`BufferedReader`类:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ArrayInput {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int[] myArray = new int;
for (int i = 0; i < myArray.length; i++) {
System.out.print("Enter value for index " + i + ": ");
try {
myArray[i] = Integer.parseInt(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
reader.close();
// 可以在这里添加代码来使用数组
}
}
3. 使用`Arrays.stream()`方法:
```java
import java.util.Arrays;
import java.util.Scanner;
public class ArrayInput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size = input.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the array elements:");
for (int i = 0; i < size; i++) {
myArray[i] = input.nextInt();
}
input.close();
// 可以在这里添加代码来使用数组
}
}
以上是几种常见的方法,您可以根据自己的需要选择合适的方法来从控制台输入数组。