如何在 Java 中获取数组输入

在本指南中,您将学习如何在 Java 中输入一维数组和二维数组。我们将使用for 循环和Scanner 类来完成此操作。

Java 程序输入一维数组

import java.util.Scanner;public class ArrayInputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Prompt user to enter the array size System.out.print("Enter the size of the array: "); int size = scanner.nextInt(); //Declare array based on entered size 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 num : array) { System.out.print(num + " "); } scanner.close(); }}

输出

Enter the size of the array: 5Enter the elements of the array:1020304050Array elements:10 20 30 40 50

注意事项

您需要导入java.util.Scanner包才能使用 Scanner 类的各种方法。

请务必使用 scanner.close() 在完成读取用户输入后释放资源。

Java 程序输入二维数组

这里的方法类似,但是为了输入二维数组,我们需要使用嵌套的 for 循环。此外,我们需要从用户那里获取额外的行和列输入。

import java.util.Scanner;public class TwoDArrayInputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows: "); int rows = scanner.nextInt(); System.out.print("Enter the number of columns: "); int cols = scanner.nextInt(); int[][] array = new int[rows][cols]; System.out.println("Enter the elements of the array:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { array[i][j] = scanner.nextInt(); } } // Print the array System.out.println("Array elements:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(array[i][j] + " "); } // Move to the new line after printing each row System.out.println(); } scanner.close(); }}

输出

Enter the number of rows: 2Enter the number of columns: 3Enter the elements of the array:102030405060Array elements:10 20 30 40 50 60

注意事项

您必须确保输入值由空格或换行符分隔。

在上述程序中,我们使用的是整型数组,但您可以修改程序以处理其他类型的数组,例如双精度型或字符串型数组。这可以通过更改数组的数据类型并将 nextInt() 方法替换为适当的方法(例如 nextDouble() 或 nextLine() )来轻松完成。

热门相关文章

何时在 Java 中使用 ArrayList 和 LinkedList

从Java字符串中删除特殊字符

如何编译和运行你的第一个 Java 程序

Java Scanner 类及示例

将逗号分隔的字符串转换为 Java HashSet

Copyright © 2088 《一炮特攻》新版本全球首发站 All Rights Reserved.
友情链接