从键盘输入数组:使用 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 + " "); } } }
以上就是java 怎么从键盘输入数组的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号