简体   繁体   English

使用for循环在Java中绘制围栏

[英]Draw a fence in Java using for loops

I am tasked to make a fence drawing program. 我受命编写一个围栏绘图程序。 So far I can have the user input values to set height and width and using nested for loops I can get it to output the height and width as a "#" symbol. 到目前为止,我可以让用户输入值来设置高度和宽度,并且使用嵌套的for循环,我可以得到它以“#”符号的形式输出高度和宽度。 The problem is I need it to have a border of # with | 问题是我需要它与#的边界为|。 in the middle. 在中间。

Currently a 4 height 4 width fence looks like this 当前4高度4宽度的围栏看起来像这样

####     
####
####
####

I need it to look like this 我需要它看起来像这样

####
#||#
#||#
####


   public void draw() {
       for (i = 1; i < height-1; i++) {
           System.out.print("#");
           for (j = 1; j < width-1; j++) {
               System.out.print("|");
           }
           System.out.println("#");
       }
       fenceCount++;
   }

When is it ok to use a break. 什么时候可以休息一下。 I have a loop asking if the user would like to build another fence type y or n. 我有一个循环,询问用户是否要构建其他类型的y或n。 At the end for the terminating user input "n" does anyone know if there is a better way to do this than a break; 最后,对于终止用户输入“ n”,没有人知道是否有比中断更好的方法; ? and is a single break "ok" here? 可以在这里休息一下吗? I have heard breaks are sloppy in loops. 我听说休息很随意。 Also I always feel like I have to reverse my thinking on while loops. 同样,我总是觉得我不得不在while循环上扭转思路。

Your fence output will currently be entirely filled with '#' 您的篱笆输出当前将全部用“#”填充
You are right in saying that the top and bottom rows there will be only '#' 您说对了,最上面和最下面的行只有“#”

For the remaining rows, for the entry in the first and the last column you need a #, else a | 对于其余的行,对于第一列和最后一列中的条目,您需要一个#,否则需要一个|。

Here is somthing to help: 这里有一些帮助:

for (i = 1; i <= height; i++)
   {
     if(first or last row)
     {
        for (j = 1; j <= width; j++)
        {
         print#
        }
     }
     else{
           for (j = 1; j <= width; j++)
           {
               if(j=1 or j=last column)
                   print '#'
               else
                   print '|'
           }
         }
      System.out.println();
   }

This will build you fence well:-) 这样可以很好地建立篱笆:-)

Change draw() to: draw()更改为:

public void draw() {
    String border = String.format("%0" + width +"d", 0).replace("0", "#");
    System.out.println(border); // top-border
    for (int i = 1; i < height-1; i++) {
        System.out.print("#"); 
        for (int j = 1; j < width-1; j++) {
            System.out.print("|");
        }
        System.out.println("#");
    }
    System.out.println(border); // bottom-border
}

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

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