Java String square pattern

时间:2019-01-18 18:54:02

标签: java string sequence

A user enters a String and method draws a square. For example:

  • For input= ram method draws:
    r r r
    - a -
    m m m
  • For input= code method draws:
    c c c c
    - o o -
    - d d -
    e e e e
  • For input = coder method draws:
    c c c c c
    - o o o -
    - - d - -
    - e e e -
    r r r r r

So far I have managed to draw something like this:
c - - - c
- o - o -
- - d - -
- e - e -
r - - - r

Using this code:

static void pattern(String n) {
        int len = n.length();

        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                if((i==j)||(i==len-j-1)) {
                    System.out.printf("%c ", n.charAt(i));
                } else {
                    System.out.printf("- ");
                }
            }
            System.out.printf("%n");
        }

    }

I have only managed to print diagonally using if((i==j)||(i==len-j-1)), but I do not know how I would be able to make it look like example above. How could I upgrade my code to draw the square properly?

2 个答案:

答案 0 :(得分:3)

static void pattern(String n) {
        int len = n.length();
for (int i = 0; i < len; i++) {
    for (int j = 0; j < len; j++) {
        if((i<j)&&(i>len-j-1) || (i>j)&&(i<len-j-1)) {
            System.out.printf("- ");

        } else  {
            System.out.printf("%c ", n.charAt(i));
        }
    }
    System.out.printf("%n");
}

The first condition

 (i>j)&&(i<len-j-1)

selects the following part

x x x x x x x
- x x x x x x
- - x x x x x
- - - x x x x
- - x x x x x
- x x x x x x
x x x x x x x

and the

 (i>j)&&(i<len-j-1)

selects the following parts

x x x x x x x
x x x x x x -
x x x x x - -
x x x x - - -
x x x x x - -
x x x x x x -
x x x x x x x

答案 1 :(得分:2)

You could use double for loop to print 2D array. Just count amount of - at the beginning and end of the raw depending on the raw's index.

public static void pattern(String str) {
    for (int i = 0, last = str.length() - 1; i <= last; i++) {
        for (int j = 0, dash = last; j <= last; j++, dash--)
            System.out.print(i < j && i > dash || i > j && i < dash ? '-' : str.charAt(i));

        System.out.println();
    }
}