首页 > 解决方案 > 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();
}

标签: javaarraysmatrixmultidimensional-array

解决方案


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.


推荐阅读