Mariana Mitru Mariana Mitru - 1 month ago 7
Java Question

How can I make a border to a matrix in java?

I have this matrix :

So 2 line and 2 columns.


  • 1 2

  • 3 4



I have the reading function

for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
try {// System.out.println("number is ");
a[i][j] = scanner.nextInt();

} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix


How can I make a border to a matrix? I've seen that in java there is no index -1.

I want a border with a number. For example :
0 0 0 0


  • 0 0 0 0

  • 0 1 2 0

  • 0 3 4 0

  • 0 0 0 0



How should I make that border function?

Answer

First you need to create the matrix with extra rows and columns, for example in your case a 4x4 matrix. and them put 0 on the borders

when i==0 or i==n-1, j==0 or j==n-1,

int a[][] = new int[4][4];
int n,m;
n=4;
m=4;
for(int i=0;i<m;i++){
 for(int j=0;j<n;j++){
  if(i==0 || j==0 || i==m-1 || j==n-1){
   //a[i][j] = 0; 
   a[i][j] = 1;
   }
   System.out.print(a[i][j]+" ");
 }
  System.out.println();
}

then

for (int i = 1; i < m-1; i++) {
                for (int j = 1; j < n-1; j++) {
                    try {//    System.out.println("number is ");
                        a[i][j] = scanner.nextInt();

                    } catch (java.util.NoSuchElementException e) {
                        // e.printStackTrace();
                    }
                }
            }         //print the input matrix