Skip to content

Instantly share code, notes, and snippets.

@vakho10
Created September 20, 2018 07:21
Show Gist options
  • Save vakho10/af84935c9d031f29d2a2f657fc12fe53 to your computer and use it in GitHub Desktop.
Save vakho10/af84935c9d031f29d2a2f657fc12fe53 to your computer and use it in GitHub Desktop.
Simple Java applictaion which draws pyramids in the console.
package ge.tsu.pyramid;
public class Main {
public static void main(String[] args) {
// Pyramid properties
char symbol = '+';
int height = 10;
PyramidPrinter printer = new PyramidPrinter();
// Left pyramid
System.out.println(printer.getLeftPyramidOfHeight(height, symbol));
// Right pyramid
System.out.println(printer.getRightPyramidOfHeight(height, symbol));
// Center pyramid
System.out.println(printer.getCenterPyramidOfHeight(height, symbol));
}
static class PyramidPrinter {
String getLeftPyramidOfHeight(int height, char symbol) {
String str = "";
for (int i = 0; i < height; i++) {
for (int j = 0; j <= i; j++) {
str += symbol;
}
str += "\n";
}
return str;
}
String getRightPyramidOfHeight(int height, char symbol) {
String str = "";
for (int i = 0; i < height; i++) {
for (int j = height; j >= 0; j--) {
if (j <= i) {
str += symbol;
} else {
str += " "; // Empty space
}
}
str += "\n";
}
return str;
}
String getCenterPyramidOfHeight(int height, char symbol) {
int width = 2 * height - 1;
String str = "";
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int center = width / 2;
if (j >= center - i && j <= center + i) {
str += symbol;
} else {
str += " ";
}
}
str += "\n";
}
return str;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment