0

I am studying and have a little trouble. I have to build matrix like this on the picture Matrix

But i can't put a stars in that places.

public static void main(String[] args) {
    int[][] twoD = new int[5][5];
    int i, j, k = 1;
    for (i = 0; i < 5; i++) 
    for (j = 0; j < 5; j++) {
            twoD[i][j] = k;
            k++;
    }
    for (i = 0; i < 5; i++) {
    for (j = 0; j < 5; j++)
    System.out.print(twoD[i][j] + " ");
        System.out.print("\n");
    }
}

Here is my code, please help to find

1

2 Answers 2

1

You can take the answer from a previous question and slightly modify it like so

public static void printCross(int size, char display)
{
    int count = 0; //add a counter
    for (int row = 0; row < size; row++) {
        for (int col = 0; col < size; col++) {
            count++; //increment each index we come across
            if (row == col || row + col == size - 1) {
                //print out the X using teh given display character
                System.out.print(String.format("%-3s", display));
            } else {
                //print out the current count
                System.out.print(String.format("%-3s", count));
            }
        }
        System.out.println();
    }
}

Output

X  2  3  4  X  
6  X  8  X  10 
11 12 X  14 15 
16 X  18 X  20 
X  22 23 24 X  
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot, I will try.
0

I have found the easiest way i think.

public static void main(String args[]){
    String[][] Matrix = { {" *"," 2"," 3"," 4"," *"} , {" 6"," *"," 8"," *","10"} , {"11","12"," *","14","15"} , {"16"," *","18"," *","20"} , {" *","22","23","24"," *"}};
    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("");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.