java - 尽管我确保数组索引小于数组大小,但如何修复数组索引超出范围?
问题描述
我创建了一个名为 Matrix 的类,在其中借助一些方法,我可以将矩阵的顺序和矩阵的元素作为用户的输入。当我运行代码时,它要求我输入矩阵的顺序,然后不是要求我输入矩阵的元素,而是给出错误“java.lang.ArrayIndexOutOfBoundsException”。你可以看看代码。
import java.util.Scanner;
public class Matrix {
int mRow;
int nColumn;
Scanner input = new Scanner(System.in);
void getInput() {
System.out.println("Enter number of rows:");
mRow = input.nextInt();
System.out.println("Enter number of columns:");
nColumn = input.nextInt();
}
int a[][] = new int[mRow][nColumn];
void getElement() {
System.out.println("Enter the elements of the matrix: ");
for (int i = 0; i < mRow; i++) {
for (int j = 0; j < nColumn; j++) {
a[i][j] = input.nextInt();
}
}
}
void showMatrix() {
for (int i = 0; i < mRow; i++) {
for (int j = 0; j < nColumn; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
[1]: https://i.stack.imgur.com/guyRk.png
解决方案
确保在收到输入时更新数组,即。
void getInput() {
System.out.println("Enter number of rows:");
mRow = input.nextInt();
System.out.println("Enter number of columns:");
nColumn = input.nextInt();
a = new int[mRow][nColumn]; // you need this line
}
推荐阅读
- macos - 每次我使用并行时我都必须下载debian吗?
- java - 为什么不会打印数组的正确中位数?
- python - 检测图像中网络链接周围的网络创建矩形
- javascript - 多次调用 React 组件
- android - 自定义项目布局气泡像 Messenger 一样聊天
- javascript - 如何在无状态 ScrollViewRTL 组件中使用 ref?
- unity-container - Prism 7.1 和 Unity 拦截器
- java - 使用 Spring 进行休眠映射
- c# - 实例化一个非静态类以跨其他类使用而无需继承
- css - Untouched Create React App 体验 Flash of Unstyled Content