简体   繁体   English

从Java中的用户输入绘制空心星号正方形/矩形

[英]Drawing a hollow asterisks square/rectangle from user input in Java

I'm trying to create a program which asks the user for the width and length dimensions of a square/rectangle and then draws it out using the # symbol. 我正在尝试创建一个程序,要求用户提供正方形/矩形的宽度和长度尺寸,然后使用#符号将其绘制出来。 I've almost got it, except I can't quite seem to get the right side of the rectangle to print out right... Here's my code: 我已经准备好了,除了我似乎不太了解矩形的右边以正确打印出来。这是我的代码:

import java.util.Scanner;
public class warmup3
{
  public static void main(String[] args)
  { 
    int width; 
    int length;

    Scanner sc= new Scanner(System.in);

    System.out.println("How big should the width of the square be?");
    width = sc.nextInt();

    System.out.println("How big should the length of the square be?");
    length= sc.nextInt(); 

    {
    for (int y= 0; y < length; y++)
    {
      for (int x= 0; x < width; x++)
      { 
        if (x == 0 || y == 0)
        {
          System.out.print("#");
        }
        else if (x != width && y == length-1)
        {
          System.out.print("#");
        }
        else if (y != length && x == width-1)
        {
          System.out.print("#");
        }
        else
        {
           System.out.print("");
        }
      }
    System.out.println("");
    }
    }
  }
}

I know the problem is with the second else-if statement but I am unable to fix it... 我知道问题出在第二个else-if语句上,但是我无法解决它...

I am unable to upload a picture of what this code prints out but basically it's an almost complete rectangle but with two rows of #s on the left side and none enclosing the right side (right side is open) (you should be able to see for yourself). 我无法上传此代码打印出的图片,但基本上是一个几乎完整的矩形,但左侧有两排#,而没有封闭右侧(右侧是打开的)(您应该可以看到为自己)。

The problem is actually with the last else statement. 问题实际上出在最后的else语句上。 Instead of printing out "nothing" or "" you need to print out a space " " . 无需打印出“ nothing”或""您需要打印出一个空格" " So change the else statement to: 因此,将else语句更改为:

    else
    {
       System.out.print(" ");
    }

That way when the loop is currently not at any of the edges it will print out a space, allowing the last else if to be in the proper location when printing out the last # 当循环是目前没有任何可打印出一个空间的边缘,从而使最后这样, else if要打印出最后的时候是在正确的位置#

Iterate as 2 dimensional array with logical checks: 通过逻辑检查迭代为二维数组:

public static void rectOuter(int length, int width) {

    String printStr = "*";
    String seprator = " ";

    for (int i = 0; i < length; i++) {

        for (int j = 0; j < width; j++)

            if (i == 0 || j == 0 || i == length - 1 || j == width - 1)
                System.out.print(printStr + seprator);
            else
                System.out.print(seprator + seprator);

        System.out.println();
    }
}

PS: System.out.print to be replaced with StringBuilder PS:System.out.print将替换为StringBuilder

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

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