java - Setting a char value to a 2d array
问题描述
I am making a 3x3
matrix using a 2d array. The array will initially display all -
. Afterwhich I try to update the some values of the array to 1
and 2
. But the display still shows all -
without updating the values of the array.
private char[][] matrix;
public Matrix() {
matrix = new char[3][3];
}
// setter and getter
public void set(int rowIndex, int colIndex, char data) {
matrix[rowIndex][colIndex] = data;
}
public int get(int rowIndex, int colIndex) {
return matrix[rowIndex][colIndex];
}
// display the matrix
public void display() {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = '-';
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
public static void println(String message) {
System.out.println(message);
}
public static void main(String[] args) {
Matrix matrix = new Matrix();
matrix.display();
matrix.set(0, 0, '1');
matrix.println("");
matrix.display();
matrix.set(0, 1, '2');
matrix.println("");
matrix.display();
}
解决方案
That is because your display()
method is always resetting the values of the array to -
before printing it.
You should remove that line from the method.
If you want to initialize your matrix with certain values you should do that in the constructor.
推荐阅读
- python - 找不到页面错误 404 django 导航栏链接
- ruby-on-rails - 使用 Rails 关联而不是实例方法
- javascript - 在 ASP.NET Core 中使用 ajax 向控制器发送数据
- c++ - 为什么结构内部的对象初始化不同?
- reactjs - 使用 React 的 HashRouter 时如何从 URL 中删除 static/index.html?
- cardano - PlutusPlayground [高 REDEEM 费用]
- visual-studio - 双重包含的问题
- math - 旋转图像后的裁剪/缩放公式
- flutter - 相关的导致错误的小部件是 TextField
- linux - Docker standard_init_linux.go:228: exec 用户进程导致:没有这样的文件或目录