乘以字符串

时间:2015-10-01 01:17:59

标签: java string for-loop

说我想制作一些看起来像这样的“塔”:

*********
*********
********* *******
********* *******
********* ******* ***************
********* ******* ***************
********* ******* ***************
********* ******* ***************
********* ******* ***************
********* ******* ***************
********* ******* ***************

如果我要求用户为塔的宽度输入三个不同的数字并且随机整数将构成长度,我该如何制作一个for循环,它将乘以“*”乘以用户为宽度输入的数字?这就是我到目前为止所做的:

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

            // I would like to do something like 
            // System.out.print("*") * width1
            // and do this for all three towers so that they 
            // print next to each other separated by a space
        }

2 个答案:

答案 0 :(得分:1)

使用以下代码块替换for循环应该有效。

int highest = Math.max(randInt1, Math.max(randInt2, randInt3));
for(int i = highest; i > 0; i--){
    printColumn(width1, randInt1, i);
    System.out.print(" ");

    printColumn(width2, randInt2, i);
    System.out.print(" ");

    printColumn(width3, randInt3, i);
    System.out.println();
}

添加辅助方法

private static void printColumn(int columnWidth, int columnHeight, int currentHeight) {
    for(int j = columnWidth;j > 0;j--) {
        if(columnHeight - currentHeight >= 0) {
            System.out.print("*");
        } else {
            System.out.print(" ");
        }
    }
}

你无法“乘”“*”。您可能希望逐行打印塔,并使用空间对齐每列。

答案 1 :(得分:0)

另一种解决方案是每行连接每个塔的星形或白色空间。注意generateString(),它返回相关塔宽度的字符串!

public static void main(String[] args) {

    // hardcoded settings (example) 
    // in your case you'll read it from the user
    Integer[] widths = {5, 4, 6};
    Integer[] heights = {5, 4, 6};

    // subtract max-1 from the heights
    int max = Collections.max(Arrays.asList(heights)) - 1;
    for (int i=0; i<heights.length; i++)
        heights[i] -= max;


    // print the towers
    for (int i=0; i<max; i++){
        String line = "";
        for (int j=0; j<widths.length; j++) {
            if (heights[j] > 0)
                line += generateString("*", widths[j]) + " ";
            else
                line += generateString(" ", widths[j]) + " ";
            heights[j] += 1;
        }
        System.out.println(line);
    }
}

private static String generateString(String str, int times) {
    return String.format("%1$" + times + "s", str).replace(" ", str);
}