简体   繁体   English

如何使用两个for循环制作形状

[英]how to make a shape using two for loops

How can I make shapes using two for loops? 如何使用两个for循环制作形状? I can't seem to get the increments correct and I'm unsure how it should be nested. 我似乎无法正确获得增量,并且不确定如何嵌套。 I understand how to make a hollow box with stars but cannot figure out how to produce these: 我知道如何用星星制作空心盒子,但不知道如何制作这些星星:

星号和斜线

This is the code I have tried: 这是我尝试过的代码:

System.out.print("How big should the shape be? ");

Scanner scr = new Scanner(System.in); 

int x = scr.nextInt(); 
drawShape(x);  

public static void drawShape(int x) {
  for(int i = 1; i <= x + 1; i++) {
    System.out.println("//\\\\");
    System.out.print("/");
    for(int j = 1; j <= x * 2; j++) {
      System.out.print("**");
    }
    System.out.print("\\");
    System.out.println("//\\\\");
  }
}

If I understood the problem correctly then here is a quick code snippet. 如果我正确理解了问题,那么这里是一个快速代码段。

Change your drawShape() method like this: 像这样更改您的drawShape()方法:

public static void drawShape(int x) {
    /* Start Printing Shapes */
    for(int i = 2; i <= x; i++) {
        /* Set Open */
        char[] open = new char[i];
        Arrays.fill(open,'/');

        /* Set Close */
        char[] close = new char[i];
        Arrays.fill(close,'\\');

        /* Set Stars */
        char[] astx = new char[i*2 - 2];
        Arrays.fill(astx,'*');

        /* Print Header */
        System.out.println(new String(open) + new String(close));
        /* Print Stars */
        System.out.println("/" + new String(astx) + "/");
        /* Print Footer */
        System.out.println(new String(close) + new String(open));
    }

    /* Line Break */
    System.out.println();
}

Here is another solution using loops: 这是使用循环的另一种解决方案:

public static void drawShape(int x) {
    /* Start Printing Shapes */
    for(int i = 2; i <= x; i++) {
        /* Set Open & Close */
        char[] open = new char[i];
        char[] close = new char[i];
        for(int k = 0; k < i; k++) {
            open[k] = '/';
            close[k] = '\\';
        }

        /* Set Stars */
        char[] astx = new char[i*2 - 2];
        for(int k = 0; k < i*2 - 2; k++) {
            astx[k] = '*';
        }

        /* Print Header */
        System.out.println(new String(open) + new String(close));
        /* Print Stars */
        System.out.println("/" + new String(astx) + "/");
        /* Print Footer */
        System.out.println(new String(close) + new String(open));
    }

    /* Line Break */
    System.out.println();
}

Here is the output of this program: 这是该程序的输出:

//\\
/**/
\\//
///\\\
/****/
\\\///
////\\\\
/******/
\\\\////

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

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