◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
从键盘输入数组:使用 scanner 类,从键盘读取输入,存储到数组中。使用 bufferedreader,逐行读取输入,转换为数字,存储到数组中。
从键盘输入数组
从键盘输入数组是将用户输入的值存储到 Java 数组中的过程。这里介绍两种方法来实现这一目的:
方法 1:使用 Scanner 类
示例代码:
立即学习“Java免费学习笔记(深入)”;
import java.util.Scanner; public class InputArrayFromKeyboard { 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[] array = new int[size]; System.out.println("Enter the elements of the array: "); for (int i = 0; i < size; i++) { array[i] = scanner.nextInt(); } // Print the array System.out.println("Array elements: "); for (int element : array) { System.out.print(element + " "); } } }
方法 2:使用 BufferedReader
示例代码:
立即学习“Java免费学习笔记(深入)”;
import java.io.BufferedReader; import java.io.InputStreamReader; public class InputArrayFromKeyboard { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the size of the array: "); int size = Integer.parseInt(reader.readLine()); int[] array = new int[size]; System.out.println("Enter the elements of the array: "); for (int i = 0; i < size; i++) { array[i] = Integer.parseInt(reader.readLine()); } // Print the array System.out.println("Array elements: "); for (int element : array) { System.out.print(element + " "); } } }
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。