【问题标题】:Repeat single char to char array. set length of array to match the needed length for string重复单个字符到字符数组。设置数组的长度以匹配字符串所需的长度
【发布时间】:2016-06-10 11:20:42
【问题描述】:

我正在使用扫描仪输入单个字符。该字符需要根据需要重复多次以构建特定形状。 例如:

AAAAA   <<< this would be a square made from the char A
AAAAA
AAAAA

我有一个超类 Shape 和子类 square、diamond、circle。 shapeString 是 Shape 中使用的公共静态变量,用于显示根据使用的 char 构建的字符串。这是我设置所需数组长度的 for 循环。我需要帮助将数组的长度设置为循环大小。

System.out.println("Type an upper or lower case letter or one of these special characters: !, #, $, %, &, (, ), *, + Press ENTER");
setChar = input.next(); 
char[] stringSetChar = setChar.toCharArray();
for(int i = 0; i < shapeString.length(); i++ {
  stringSetChar.length([i]); // help here!
  shapeString = new String(stringSetChar);
}

【问题讨论】:

  • 好吧,显然我以为你可以看到 A 是如何形成正方形的。哈哈。对不起
  • 改用java.util.Scanner.nextLine() 方法。会更容易。
  • 形状的大小总是一样的吗?

标签: java arrays string


【解决方案1】:

我将使用传递给Shape 的构造函数的“模板”字符串,并让Shape 实现一个draw() 方法,该方法使用模板通过将占位符字符替换为所需的字符来创建输出:

abstract class Shape {
    private final String template;

    protected Shape(String template) {
        this.template = template;
    }

    public void draw(char c) {
        System.out.println(template.replace('.', c));
    }
}

class Square extends Shape {
    public Square() {
        super(".....\n.....\n.....\n");
    }
}

这些方法允许绘制任意形状(例如字母、表情符号等)。


一些测试代码:

new Square().draw('A');

输出:

AAAAA
AAAAA
AAAAA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2017-08-19
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多