Reputation:
Code
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("");
}
}
I'm having a trouble compiling the pyramid correctly. Instead it simply prints a vertical pattern with the correct number of asterisks.
Upvotes: 1
Views: 179
Reputation: 521997
Your code is actually correct, except for one minor detail. You are calling println
everywhere, which will always print to a newline. Instead, only call println
at the end of each line, but use just print
when you want to build out a given line with stars and spaces. Using this version of your code:
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);
I get the correct output:
*****
***
*
Upvotes: 5