在 Java 中輸入數組的方法包括:使用 Scanner 類輸入整數數組。使用 BufferedReader 類輸入字串數組。使用 DataInputStream 類輸入基本類型資料數組(例如整數數組)。

如何在 Java 中输入一个数组
在 Java 中,可以使用以下方法输入一个数组:
1. 使用 Scanner 类
Scanner 类提供了一组方法用于从控制台读取输入。可以使用以下代码来输入一个整数数组:
立即学习“Java免费学习笔记(深入)”;
<code class="java">import java.util.Scanner;
public class ReadArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
// Display the elements of the array
System.out.println("Elements of the array:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}</code>2. 使用 BufferedReader 类
BufferedReader 类提供了一个 readLine() 方法,用于逐行读取文本。可以使用以下代码来读取一个字符串数组:
<code class="java">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadArray {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of the array:");
int size = Integer.parseInt(reader.readLine());
String[] arr = new String[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = reader.readLine();
}
// Display the elements of the array
System.out.println("Elements of the array:");
for (String s : arr) {
System.out.print(s + " ");
}
}
}</code>3. 使用 DataInputStream 类
DataInputStream 类提供了用于读取基本类型数据的 readInt() 和 readUTF() 方法。可以使用以下代码来读取一个整数数组:
<code class="java">import java.io.DataInputStream;
import java.io.IOException;
public class ReadArray {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the size of the array:");
int size = dis.readInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = dis.readInt();
}
// Display the elements of the array
System.out.println("Elements of the array:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}</code>以上就是java怎么实现输入一个数组的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号