user3006901
user3006901

Reputation:

how to create a square using for loops

I need help making a program where you allow the user to enter a character and a number and output a square on the screen which consists of the character with sides equal to the number entered.

e.g. User enters $ and 5 – and outputs

            $$$$$
            $   $
            $   $
            $   $
            $$$$$    

I tried this so far, but I don't know how to get rid of the characters inside the box.

int r,c;
System.out.println (" Please enter the number of rows for the rectangle.");
r=sc.nextInt();
System.out.println (" Please enter a character for the rectangle.");
c=sc.nextInt();
for (int x=r;x>=1;--x) {
    for (int y=r;y>=1;y--) {
        System.out.print (c);
    }
    System.out.println (c);
}

Upvotes: 0

Views: 10025

Answers (2)

Ryan Stein
Ryan Stein

Reputation: 8000

You said about your example that you don't know how to get rid of the characters in the box. I believe the best way to get rid of something you don't want is to not put it there in the first place. Let's think about your problem a little.

Based on your example, you want a square box of characters enclosing some whitespace, correct? This fundamentally breaks down into two different lines. These are the two horizontal edges and the r-2 vertical edges.

We can build a simple algorithm from this.

Scanner s = new Scanner(System.in);
int r;
String c;
String h, v;

// Get input from the user.
System.out.println("Please enter the number of rows for the rectangle.");
r = s.nextInt();
System.out.println("Please enter a character for the rectangle.");
c = s.next();

// Make the box's lines.
h =     new String(new char[r  ]).replace("\0",  c);
v = c + new String(new char[r-2]).replace("\0", " ") + c;

System.out.println(h);
for (int i=r-2; i>=1; --i) {
    System.out.println(v);
}
System.out.println(h);

For a little more material on repeating strings, see here, and here for user input in Java. I hope this has been of some help. I leave handling squares of size r<2 as an exercise to the reader.

Upvotes: 1

aib
aib

Reputation: 46921

char c = '$';
int n = 5;

for (int i=0,m=n+1; i<m*n; ++i) {
    putchar(i%m==n?'\n':(i+m)%(m*n)<2*m?c:(i+m+2)%m<3?c:' ');
}

Upvotes: 1

Related Questions