Categories

# 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: ");
int n = Integer.parseInt(br.readLine());
if(n < 4 || n > 9){
System.out.println("Size out of range!");
return;
}
char m[][] = new char[n][n];
System.out.print("First character: ");
char first = br.readLine().charAt(0);
System.out.print("Second character: ");
char second = br.readLine().charAt(0);
System.out.print("Third character: ");
char third = br.readLine().charAt(0);
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[0][0] = first;
m[n - 1][n - 1] = first;
m[0][n - 1] = first;
m[n - 1][0] = 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 replies on “Fill Matrix with Three Characters in Java”

sayan ranasays:

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