I've been trying to get this done in Java. And this is a complex thing to draw, at least for me.
Q1 Write a simple Java program that prints a staircase or a figure as shown below:
+---+
| |
+---+---+
| | |
+---+---+---+
| | | |
+---+---+---+---+
| | | | |
+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+
I have come up with a solution but it is not even halfway there. This is the code I have come up with
public class DrawStairs {
public static final int HEIGHT = 5;
public static final int TOTALHEIGHT = HEIGHT * 5;
public static void main(String[] args) {
//Main Outer Loop
for (int i = 1; i <= HEIGHT; i++) {
//Loop for the spaces before, then print the head
for (int j = 1; j <= TOTALHEIGHT + (i * (-5)); j++) {
System.out.print(" ");
}
printTop();
//Loop for spaces after, then print asterisk
for (int j = 1; j <= (i - 1); j++) {
System.out.print("---+");
}
System.out.println(" ");
//Loop for the spaces before, then print the body
for (int j = 1; j <= TOTALHEIGHT + (i * (-5)); j++) {
System.out.print(" ");
}
printMiddle();
//Loop for spaces after, then print asterisk
for (int j = 1; j <= (i - 1) * 5; j++) {
System.out.print(" ");
}
//Loop for spaces before, then print the legs
for (int j = 1; j <= TOTALHEIGHT + (i * (-5)); j++) {
System.out.print(" ");
}
printBottom();
//Loop for spaces after, then print asterisk
for (int j = HEIGHT; j <= 0; --j) {
System.out.print("---+");
}
System.out.println("|");
}
// for loop for printing the floor of asterisks
for (int i = 1; i <= HEIGHT; i++) {
System.out.print("+---+");
}
}
public static void printTop() {
System.out.print("+---+");
}
public static void printMiddle() {
System.out.print("| |");
}
public static void printBottom() {
// System.out.print("+---+");
}
}
And this is what it does.
+---+
| | |
+---+---+
| | |
+---+---+---+
| | |
+---+---+---+---+
| | |
+---+---+---+---+---+
| | |
+---++---++---++---++---+
Can anyone please help me and guide me with my code? I'd like if someone can tell me what's wrong and what should be changed.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…