如何右对齐Floyd的2的三角幂的打印

时间:2019-11-04 02:10:20

标签: java for-loop

如何在输出弗洛伊德三角形的最后2行向左移动? 这是我的输出:

      1 
     21 
    421 
   8421 
  168421 
 32168421 

预期输出:

         1 
        21 
       421 
      8421 
    168421 
  32168421 

这是我的代码:

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

         //total of space
        int n=6-i;

         //print space
         while(n>0) {
             System.out.print(" ");
             n--;
         }

         //print number
         for(int j=i; j>=0; j--) {
             System.out.print((int)Math.pow(2, j));
         }

         System.out.println(" ");

     }

谢谢

2 个答案:

答案 0 :(得分:1)

    int lineLength = 8;

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

        //print number
        StringBuilder sb = new StringBuilder();
        for (int j = i; j >= 0; j--) {
            sb.append((int) Math.pow(2, j));
        }

        //print space
        for (int spaces = lineLength - sb.length(); spaces > 0; spaces--) {
            System.out.print(" ");
        }
        System.out.println(sb.toString());
    }

还有一个更通用的示例:

public static void main(String[] args) {

    int numbersToCompute = 10;
    int lineLength = floydsNumber(numbersToCompute).length();
    for (int i = 0; i <= numbersToCompute; ++i) {
        String floydsNumber = floydsNumber(i);
        for (int spaces = lineLength - floydsNumber.length(); spaces > 0; spaces--) {
            System.out.print(" ");
        }
        System.out.println(floydsNumber.toString());
    }
}

private static String floydsNumber(int i) {
    StringBuilder sb = new StringBuilder();
    for (int j = i; j >= 0; j--) {
        sb.append((int) Math.pow(2, j));
    }
    return sb.toString();
}

答案 1 :(得分:0)

        List<String> result = new ArrayList<>();

        for(int i=0; i<=5; ++i) {
            StringBuilder sb = new StringBuilder();
            for(int j=i; j>=0; j--) {
                sb.append((int)Math.pow(2, j));
            }
            result.add(sb.toString());
        }

        // You need to find out the longgest string for the padding left calculation
        int length = result.get(result.size() - 1).length();

        result.forEach((str -> System.out.println(padLeft(str, length))));

为填充添加直到方法:

public String padLeft(String inputString, int length) {
        if (inputString.length() >= length) {
            return inputString;
        }
        StringBuilder sb = new StringBuilder();
        while (sb.length() < length - inputString.length()) {
            sb.append(' ');
        }
        sb.append(inputString);

        return sb.toString();
    }