Samuel Tang
Samuel Tang

Reputation: 71

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();
}

Upvotes: 1

Views: 188

Answers (2)

work_for_freedom
work_for_freedom

Reputation: 11

private char[][] matrix;

public Matrix() {
    matrix = new char[3][3];
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix.length; j++) {
            matrix[i][j] = '-';
        }
    }
}

// setter and getter
public void set(int rowIndex, int colIndex, char data) {
    matrix[rowIndex][colIndex] = data;
}

public char 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++) {
            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();
}

try this!!

Upvotes: 1

Turamarth
Turamarth

Reputation: 2282

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.

Upvotes: 1

Related Questions