简体   繁体   中英

I want create a power pyramid of “*” with Java.

Input: base=2, row = 3
Output:

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

Input: base=3, row = 3
Output:

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

I have tried this way, but I spaces aren't printing properly.

import java.util.Scanner;

public class loops {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        System.out.println("enter base:");
        int base = s.nextInt();

        System.out.println("enter height:");
        int h = s.nextInt(); 


        for (int i = 1; i <= h; i++) {

            int num = (int)Math.pow(base, i);
                for(int n=h-1; n>i-1; n--) {
                        System.out.print(" ");

                  }

                for (int j = 0; j < num; j++) {
                    System.out.print("*");
                }

            System.out.println("");
        }
    }
}
import java.util.Scanner;

public class loops {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        System.out.println("enter base:");
        int base = s.nextInt();

        System.out.println("enter height:");
        int h = s.nextInt();

        int spacesNum;
        int asterisksNum;

        for (int i = 1; i <= h; i++) {

            spacesNum = (int) ((Math.pow(base, h) - Math.pow(base, i)) / 2);
            asterisksNum = (int) (Math.pow(base, i));

            for (int j = 0; j < spacesNum; j++) {
                System.out.print(" ");
            }

            for (int j = 0; j < asterisksNum; j++) {
                System.out.print("*");
            }

            System.out.println();

        }

        s.close();
    }
}

The width of space grows geometrically, just like the width of the rings, but in the opposite direction -- it's decaying. Probably the easiest way to code it is to think about the total width, and what you're taking away from it with each ring.

Your code with that taken into account:

public class loops {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("enter base:");
        int base = s.nextInt();

        System.out.println("enter height:");
        int h = s.nextInt();
        int width = (int) Math.pow(base, h); // Note the total width.

        for (int i = 1; i <= h; i++) {
            int num = (int) Math.pow(base, i);

            // The space is half of what's left after removing the ring.
            for(int j = 0; j < (width - num)/2; j++) {
                 System.out.print(" ");
            }

            for (int j = 0; j < num; j++) {
                System.out.print("*");
            }

            System.out.println("");
        }
    }
}

Your code calls System.out.print method exponential times , one call per character.

Also, System.out.println is invoked in every iteration which causes the underlying stream to flush. (refer links from michaelt in the comments).

This SO answer is a good reference.

This is NOT good approach because:

  1. h number of I/O operations are performed, which is expensive.
  2. So many method invocations of print and println reduces the readability of the code.

Compose the strings in a separate method and use System.out.print only for printing.

Please refer the code below:

    public static void main(String[] args) {
        //your code here

    int totalWidth  = (int) Math.pow(base, h);
    String output = "";

    for (int i = 1; i <= h; i++) {
        int numOfStars = (int) Math.pow(base, i);
        int numOfSpace = (int) ((totalWidth - numOfStars) / 2);
        output += composeString(' ', numOfSpace).concat(composeString('*', numOfStars ).concat("\n"));
    }
    System.out.println(output);
    }


    //Method to create String with same character repeated X number of times
    public static String composeString(char character, int x) {
        StringBuilder buf = new StringBuilder(x);
        while (buf.length() < x) {
            buf.append(character);
        }
        return buf.toString();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM