如何在Java中绘制带星号的倒金字塔

如何在Java中绘制带星号的倒金字塔,java,arrays,algorithm,Java,Arrays,Algorithm,代码 public static void main(String[] args) { String text=JOptionPane.showInputDialog("Introduce height"); int height=Integer.parseInt(text); drawInversePiramid(height); } public static void drawInversePiramid(int height){ for(int n

代码

public static void main(String[] args) {

    String text=JOptionPane.showInputDialog("Introduce height");

    int height=Integer.parseInt(text);

    drawInversePiramid(height);
}

public static void drawInversePiramid(int height){
    for(int numberasterisks=(height*2)-1,numberspaces=0;numberasterisks>0;numberspaces++,numberasterisks-=2){
        //we draw spaces
        for(int i=0;i<numberspaces;i++){
            System.out.println(" ");
        }//we draw the asterisks
        for(int j=0;j<numberasterisks;j++){
            System.out.println("*");
        }//to jump the line
        System.out.println("");
    }
}
publicstaticvoidmain(字符串[]args){
String text=JOptionPane.showInputDialog(“引入高度”);
int height=Integer.parseInt(文本);
前臂(高度);
}
公共静态空隙率(内部高度){
对于(int numbersterisks=(height*2)-1,numberspaces=0;numbersterisks>0;numberspaces++,numbersterisks-=2){
//我们画空间

对于(int i=0;i你的代码实际上是正确的,除了一个小细节。你到处调用
println
,它总是打印到一个换行符。相反,只在每行末尾调用
println
,但当你想用星号和空格构建给定行时,只需使用
print
。使用你的代码:

public static void drawInversePiramid(int height) {
    for (int numberasterisks=(height*2)-1,numberspaces=0;numberasterisks>0;numberspaces++,numberasterisks-=2){
        // we draw spaces
        for (int i=0; I < numberspaces; i++) {
            System.out.print(" ");
        }
        // we draw the asterisks
        for (int j=0; j < numberasterisks; j++) {
            System.out.print("*");
        }
        // to jump the line
        System.out.println("");
    }
}

drawInversePiramid(3);

除了一个小细节外,您的代码实际上是正确的。您在任何地方调用
println
,这将始终打印到换行符。相反,只在每行末尾调用
println
,但当您要生成带有星号和空格的给定行时,只需使用
print
de:

public static void drawInversePiramid(int height) {
    for (int numberasterisks=(height*2)-1,numberspaces=0;numberasterisks>0;numberspaces++,numberasterisks-=2){
        // we draw spaces
        for (int i=0; I < numberspaces; i++) {
            System.out.print(" ");
        }
        // we draw the asterisks
        for (int j=0; j < numberasterisks; j++) {
            System.out.print("*");
        }
        // to jump the line
        System.out.println("");
    }
}

drawInversePiramid(3);