【问题标题】:Creating a square using user input dimensions and made from character使用用户输入尺寸创建正方形并由字符制成
【发布时间】:2013-09-24 02:03:20
【问题描述】:

我正在尝试创建一个由用户输入的字符组成的正方形,并由他们选择的尺寸组成。

public class Square
{
  public static void main(String[] args)
  {
    final byte MIN_SIZE =  2,
           MAX_SIZE = 20;

    byte size;
    char fill;

    Scanner input = new Scanner(System.in);

    do
    {
      System.out.printf("Enter the size of the square (%d-%d): ",
                        MIN_SIZE, MAX_SIZE);
      size = (byte)input.nextLong();
    } while (size > MAX_SIZE || size < MIN_SIZE);
    System.out.print("Enter the fill character: ");
    fill = input.next().charAt(0);

    //This is where the code which outputs the square would be//

  }
}

一个正方形应该是什么样子的例子如下: 如果大小为5,填充为“@”

@@@@@
@@@@@
@@@@@
@@@@@
@@@@@

【问题讨论】:

  • 糟糕的是字符不是正方形的。从技术上讲,你永远不会有正方形。

标签: java loops methods method-chaining


【解决方案1】:

您不应该要求 nextLong 并将其保存在一个字节中。大小变量应该很长。

要打印正方形,您可以使用简单的 fors

long i,j;

for(i = 0; i < size; i++)
{
    for(j = 0; j < size; j++)
        System.out.print(fill);

    System.out.println();
}

你可以让它表现得更好,创建一个包含带有填充字符的整行的字符串,然后打印它的行数,但是对于 MAX_SIZE = 20 就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多