简体   繁体   English

Java String方形图案

[英]Java String square pattern

A user enters a String and method draws a square. 用户输入一个String,然后方法绘制一个正方形。 For example: 例如:

  • For input= ram method draws: 对于input = ram方法绘制:
    rrr
    - a -
    mmm
  • For input= code method draws: 对于input = code方法绘制:
    cccc
    - oo -
    - dd -
    eeee
  • For input = coder method draws: 对于输入= coder方法绘制:
    ccccc
    - ooo -
    - - d - -
    - eee -
    rrrrr

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. 我只能使用if((i==j)||(i==len-j-1))对角打印,但是我不知道如何使它看起来像上面的示例。 How could I upgrade my code to draw the square properly? 如何升级代码以正确绘制正方形?

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

You could use double for loop to print 2D array. 您可以使用double for循环来打印2D数组。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM