跳转到主内容
新派编程网 - 新潮编程理念,全新技术课堂!

java怎么实现输入一个数组

在 Java 中輸入數組的方法包括:使用 Scanner 類輸入整數數組。使用 BufferedReader 類輸入字串數組。使用 DataInputStream 類輸入基本類型資料數組(例如整數數組)。 如何在 Java 中输入一个数组 在 Java 中,可以使用以下方法输入一个数组: 1. 使用 Scanner 类 Scanner 类提供了一组方法用于从控制台读取输入。可以使用以下代码来输入一个整数数组: 立即学习 “ Java免费学习笔记(深入) ”; php字符串与byte字节数组转化类 php字符串与byte字节数组转化类 下载
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 + " "); } } }
2. 使用 BufferedReader 类 BufferedReader 类提供了一个
readLine()
方法,用于逐行读取文本。可以使用以下代码来读取一个 字符串数组 :
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 + " "); } } }
3. 使用 DataInputStream 类 DataInputStream 类提供了用于读取基本类型数据的
readInt()
和
readUTF()
方法。可以使用以下代码来读取一个整数数组:
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 + " "); } } }

相关文章