java如何从键盘上输入二维数组_string字符串转为数组

java如何从键盘上输入二维数组_string字符串转为数组在 Java 中 从键盘输入二维数组可以通过以下几种方法实现 1 逐行输入 javaimport java util Scanner public class Main public static void main String args Scanner scanner new Scanner System in System out

在Java中,从键盘输入二维数组可以通过以下几种方法实现:

1. 逐行输入:

 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入二维数组的行数:"); int rows = scanner.nextInt(); System.out.println("请输入二维数组的列数:"); int columns = scanner.nextInt(); int[][] matrix = new int[rows][columns]; for (int i = 0; i < rows; i++) { System.out.println("请输入第 " + (i + 1) + " 行," + columns + " 列的素:"); for (int j = 0; j < columns; j++) { matrix[i][j] = scanner.nextInt(); } } // 打印二维数组 for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } } 

2. 使用空格分隔输入:

 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入二维数组的行数:"); int rows = scanner.nextInt(); System.out.println("请输入二维数组的列数:"); int columns = scanner.nextInt(); int[][] matrix = new int[rows][columns]; for (int i = 0; i < rows; i++) { System.out.println("请输入第 " + (i + 1) + " 行," + columns + " 列的素,用空格隔开:"); String line = scanner.nextLine(); String[] elements = line.split(" "); for (int j = 0; j < columns; j++) { matrix[i][j] = Integer.parseInt(elements[j]); } } // 打印二维数组 for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } } 

3. 使用字符串数组作为中间变量:

 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入二维数组的行数:"); int rows = scanner.nextInt(); System.out.println("请输入二维数组的列数:"); int columns = scanner.nextInt(); String[] temp = new String[rows + 1]; for (int i = 0; i < rows; i++) { System.out.println("请输入第 " + (i + 1) + " 行," + columns + " 列的素,用空格隔开:"); temp[i] = scanner.nextLine(); } int[][] matrix = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { matrix[i][j] = Integer.parseInt(temp[i].split(" ")[j]); } } // 打印二维数组 for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } } 

以上代码示例展示了如何从键盘输入一个二维数组,并将其存储在Java程序中。请根据实际需求选择合适的方法。需要注意的是,在使用`nextInt()`方法后应该调用`nextLine()`方法来消耗掉换行符,否则可能会导致输入错误。

编程小号
上一篇 2025-05-30 09:42
下一篇 2025-05-25 12:14

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/38385.html