Displaying a square based on user's input
Hello,
I have to write a program that displays hollow square with asterisks or plus sign or any sign. The sign is not important.
The size of the square is entered by the user. For example, when the user enters 1 the program displays
+++
+ +
+++
when enters 2 it displays something like this
++++
+ +
+ +
++++
and so on.Up until size 20. Basically it has to be a square, similar to the 8-bit figures displayed in DOS with asterisks or plus sign and with every bigger number inputted by the user it has to expand.
I coded up to size 2:
Code:
import java.util.Scanner;
public class Square
{
public static void main( String[] args )
{
String str = "+";
int x;
Scanner input = new Scanner(System.in);
for(int a = 1; a <= 21; a++)
{
System.out.print("\nEnter size of the side: ");
x = input.nextInt();
if( x==1 )
{
System.out.printf("%s%s%s", str, str, str);
System.out.printf("\n%s %s",str, str);
System.out.printf("\n%s%s%s",str,str,str);
}
else if( x==2 )
{
System.out.printf("%s%s%s%s",str,str,str,str);
System.out.printf("\n%s %s",str,str);
System.out.printf("\n%s %s",str,str);
System.out.printf("\n%s%s%s%s",str,str,str,str);
}
and so on
}
Is there any other way of doing this because if I keep going this way the code will become just crazy huge and full of System.out.printf methods?
2 Attachment(s)
Re: Displaying a square based on user's input
Quote:
Originally Posted by
luke
Nobody knows how to make it real square?
public
If you want to make it look and feel more semetrical. Then you can just add a space behind the asterisk and add a double space to the interior.
You can do the same with the above for loop example as well.
Attachment 3954
Code:
public static void main( String args[] ) {
Scanner input = new Scanner(System.in);
int side, width;
System.out.print("This program prints an asterisk square!");
System.out.println();
System.out.print("Enter a side length: ");
side = input.nextInt();
int hight = side;
if( side <= 20 && side > 0) {
while(height >= 1){
width = 1;
while(width <= side){
System.out.print("* "); //There is an asterisk and a space here
width++;
while(height >=2 && height <= side-1 && width <= side-1){
System.out.print(" "); //There's two spaces here
width++;
}
}
--height;
System.out.println();
}
}else{
System.out.print("Out of bounds!");
}
System.out.println();
}
:smash:
Re: Displaying a square based on user's input
This thread is almost two years old; I'm closing it.
Jos