# Fill Matrix with Three Characters in Java

Write a program to declare a square matrix m[][] of order ‘N’ where ‘N’ must be greater than 3 and less than 10. Allow the user to accept three different characters from the keyboard and fill the array according to the instruction given below:

1. Fill the four corners of the square matrix with the first character.
2. Fill the boundary of the matrix (except the four corners) with the second character.
3. Fill the non-boundary elements of the matrix with the third character.

Test your program with the following data and some random data:
INPUT:
N = 4
First character: @
Second character: ?
Third character: #
OUTPUT:
@ ? ? @
? # # ?
? # # ?
@ ? ? @

``````import java.io.*;
class FillMatrix{
public static void main(String args[])throws IOException{
System.out.print("Matrix size: ");
if(n < 4 || n > 9){
System.out.println("Size out of range!");
return;
}
char m[][] = new char[n][n];
System.out.print("First character: ");
System.out.print("Second character: ");
System.out.print("Third character: ");
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(i == 0 || j == 0 || i == n - 1 || j == n - 1)
m[i][j] = second;
else
m[i][j] = third;
}
}
m = first;
m[n - 1][n - 1] = first;
m[n - 1] = first;
m[n - 1] = first;
System.out.println("Resultant Matrix:");
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
System.out.print(m[i][j] + "\t");
}
System.out.println();
}
}
}``````

## 2 thoughts on “Fill Matrix with Three Characters in Java”

1. sayan rana on said:

Sir,how to input characters in Scanner class while doing Java programs?

• admin on said:

Use the following code to input characters using the Scanner class:
char ch = sc.next().charAt(0);

This site uses Akismet to reduce spam. Learn how your comment data is processed.