首页 > 解决方案 > 静态字符串怪异行为 Diamond Star Pattern 问题

问题描述

我正在尝试解决这个问题,给出数字 5,我们显示:

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

等等。所以你给它一个数字,它会像上面那样为你格式化。我尝试使用下面的代码解决它,但我看不到代码中的问题所在。

public class Exe01 {
    public static String space = "";//global space var 
    public static String ast = "";//global * var 


    public static String adjustAst(int numOfAst) {
        Exe01.ast = "";
        for (int i = numOfAst; i > 0; i--) {
            Exe01.ast+="*";
        }
        return Exe01.ast;
    }

    public static String adjustSpaces(int numOfSpaces) {
        Exe01.space = "";
        for (int i = numOfSpaces; i > 0; i--) {
            Exe01.space = Exe01.space + " ";
        }
        return Exe01.space;
    }

    public static void showAst(int num) {
        if (num <= 0 || num % 2 == 0)
            System.out.println("arg to the function need to be positive and odd");
        else if (num == 1)
            System.out.println("*");
        else {
            int mid = (int) (num / 2);
            int numberOfSpaces = num - 1;
            for (int i = 0; i < num; i++) {
                int k = 0;
                if (i < mid) {
                    k = k * 2 + 1;
                    System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
                    numberOfSpaces = numberOfSpaces - 2;
                } else if (i == mid) {
                    numberOfSpaces = 0;
                    k = k * 2 + 1;
                    System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
                    numberOfSpaces = numberOfSpaces + 2;
                } else {
                    k = k - 4;
                    System.out.println(Exe01.adjustSpaces(numberOfSpaces) + Exe01.adjustAst(k));
                    numberOfSpaces = numberOfSpaces + 2;
                }
            }
        }
    }

    public static void main(String args[]) {
        Exe01.showAst(5);
    }

}

在编译时它给了我这个:

    *
  *
*

标签: javaalgorithm

解决方案


推荐阅读