print a SQUARE pattern in java
Answers
HELLO THERE!
Here's a program code for printing a square in Java:
import java.util.*;
public class Square
{
public static void main (String args[])
{
Scanner sc = new Scanner (System.in);
System.out.print("Enter the size of the square: ");
int n = sc.nextInt();
System.out.print("Enter the character to print: ");
char a = sc.next().charAt(0);
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(a + " ");
}
System.out.println();
}
}
}
In the above program, I have used a Scanner class. If you are unaware of it, you may also use Stream Reader and Buffer. I have used a variable n (int) to store the size of the square, and a character a to accept the character that is to be printed. I have taken it as char because the user may give a 'number' to print, or any 'character' to print. If the user gives a number, then that number will be stored in the variable a as a character. If I would have used int datatype, it would have accepted a number, but not a character.
Look at the attachment for a sample output.
THANKS!