在Java中输入二维数组可以通过以下几种方法实现:
手动输入素
使用两个嵌套的for循环,外层循环遍历行,内层循环遍历列,逐个输入素。
Scanner input = new Scanner(System.in);
int rows = input.nextInt();
int cols = input.nextInt();
int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = input.nextInt();
}
}
逐行输入
使用`Scanner`类逐行读入素,并将每行素分割为单个素后存储在二维数组中。
Scanner input = new Scanner(System.in);
int rows = input.nextInt();
int cols = input.nextInt();
int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
String line = input.nextLine();
for (int j = 0; j < cols; j++) {
array[i][j] = Integer.parseInt(line.split(" ")[j]);
}
}
使用`Arrays.deepToString()`方法输出二维数组
import java.util.Arrays;
// ...
char[][] arr = new char[m][n];
// ...
for (int i = 0; i < m; i++) {
String s = input.next();
for (int j = 0; j < n; j++) {
arr[i][j] = s.charAt(j);
}
}
System.out.println(Arrays.deepToString(arr));
请选择适合您需求的方法进行二维数组的输入。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/143867.html