dankatle
dankatle

Reputation: 49

How to make a rectangle of characters?

How to make a rectangle of characters? I need to make such a picture appear in the console

 **********
*          *
*          *
*          *
 **********

But I get this:

********* 
********* 
********* 
********* 
********* 

Sides a and b are entered from the console.

    int a = requestNumber();
    int b = requestNumber();
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            if (j == 0 || j < (b - 1))
            System.out.print("*");
            else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

Upvotes: 1

Views: 579

Answers (2)

Victor
Victor

Reputation: 19

public class Rectangle {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle();
        rectangle.printRectangle(7,9);
    }

    private void printRectangle(int row, int col) {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if ((isFirstOrLastRow(i, row) && isFirstOrLastCol(j, col))
                        || !(isFirstOrLastRow(i, row) || isFirstOrLastCol(j, col))) {
                    System.out.print(" ");
                }
                else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }
    }

    private boolean isFirstOrLastRow(int currentRow, int row) {
        return currentRow == 0 || currentRow == row - 1;
    }

    private boolean isFirstOrLastCol(int currentCol, int col) {
        return currentCol == 0 || currentCol == col - 1;
    }
}

The four corners and the middle position should output spaces, so we should judge whether it is the four corners or the middle position,I use isFirstOrLastRow and isFirstOrLastCol to help judge.

here is the result for input 7,9

 ******* 
*       *
*       *
*       *
*       *
*       *
 ******* 

Upvotes: 1

Nathan Relyea
Nathan Relyea

Reputation: 144

A pretty concise way to do it just a few lines:

int a = requestNumber();
int b = requestNumber();

System.out.println(" " + new String(new char[a]).replace("\0", "*"));
for (int i = 0; i < b; i++) {           
    System.out.println("*" + new String(new char[a]).replace("\0", " ") + "*");
}
System.out.println(" " + new String(new char[a]).replace("\0", "*"));

EDIT: Fixed typo, works now!

Upvotes: 1

Related Questions