java - ArrayIndexOutOfBoundsException:对于arrays.main,索引 3 超出长度 3 的范围
问题描述
import java.util.Scanner;
public class arrays {
public static void main(String[] args) {
int i;
int [][] m1 = new int[2][3];
int j;
Scanner sc = new Scanner(System.in);
System.out.println(m1.length);
System.out.println(m1[0].length);
for(i = 0; i < m1.length; i++){
for(j = 0; i < m1[0].length; j++) {
m1[i][j] = sc.nextInt();
}
}
sc.close();
}
}
我无法理解为什么会发生此错误。m1.length 和 m1[0].length 打印正确的行和列长度。我给出了以下输入:
1
2
3
4
然后发生错误
解决方案
你在内部循环中有一个错字,你超出了第一轴第二个轴,因为i < m[0].length
是真的。
应该如下?
for(j = 0; j < m1[i].length; j++) {
推荐阅读
- c# - 如何在使用 UnitOfWork 时传递连接选项。C#实体框架、依赖注入、Sqlite、工作单元
- angular - Angular 原理图没有从模板创建文件
- tfs - 可以与提交关联的默认最大工作项数是多少?
- python - vsphere python 扩展 vmfs 数据存储
- php - 聚合根 ID
- java - 我已经构建了一个交互式 shell java 应用程序。我想用 Junit 5 测试它
- docker - 在 CI/CD 管道实现中为不同租户动态管理 Dockerfile
- javascript - jQuery点击动态添加的类
- mysql - SQL order元素按其他表字段但按一定顺序
- laravel - 我无法在公共 laravel 中存储上传的图像