问题
So I've been tasked with making a "Programming textbook" that can change size based off what the constant SIZE var is set at.
Here is what I have to shoot for. (NOTE: It is normal for odd-number SIZEd books to have awkward indentation towards the end). Notice how when SIZE = 8, there is one space on either side of the text, 4 spaces on either side for SIZE = 10, and so on.
Now here is what I've programmed so far. I'm almost done, the only thing I cannot figure out is the algorithm I can use to keep consistent spacing for the "label" of the book (Building Java Programs text). The commented out "TO DO" lines are where I intend to put the label of the book once I figure out the spacing
(Note: Focus on the bottomBook method. The other two methods are fine)
package bookdrawing;
public class BookDrawing
{
public static final int SIZE = 8;
public static void main(String[] args)
{
topBook();
bottomBook();
}
public static void topBook()
{
//Drawing the VERY top of the book (before starting all the loops)
for(int i = 1; i <= SIZE + 1; i++)
{
System.out.print(" ");
}
drawLine();
System.out.println();
//Main portion. Looping to draw all spaces, '/'s, '__/'s, etc.
for(int i = 1; i <= SIZE; i++)
{
//front whitespaces
for(int j = 1; j <= -1 * i + (SIZE + 1); j++)
{
System.out.print(" ");
}
//Leftmost border
System.out.print("/");
//Inner whitespaces
for(int j = 1; j <= -3 * i + (SIZE * 3); j++)
{
System.out.print(" ");
}
//Additional "_" that starts off every row
System.out.print("_");
//"__/" pattern
for(int j = 1; j <= i; j++)
{
System.out.print("__/");
}
//Right side of book (/'s)
for(int j = 1; j <= i - 1; j++)
{
System.out.print("/");
}
//Move onto the next row of book drawing
System.out.println();
}
}
private static void drawLine()
{
System.out.print("+");
//This loop grows/shrinks line body depending on value of SIZE
for(int i = 0; i <= (SIZE * 3) - 1; i++)
{
System.out.print("-");
}
System.out.print("+");
}
public static void bottomBook()
{
//Dash line on top of the bottom portion of the book
drawLine();
//Printing first set of rightmost "/"'s
for(int i = 1; i <= SIZE; i++)
System.out.print("/");
System.out.println();
for(int i = 1; i <= SIZE / 2; i++)
{
//Leftmost pipe
System.out.print("|");
// TO DO: Code label of book
// for(int j = 1; j <= ; j++)
// {
//
// }
//Rightmost pipe
System.out.print("|");
//"Pages" to right of label
for(int j = 1; j <= -2 * i + (SIZE + 2); j++)
{
System.out.print("/");
}
//Move to draw next row
System.out.println();
}
//Dash line on very bottom of entire drawing
drawLine();
}
}
And here is what my current output looks like. (The forward slash algorithm is correct, all I need to insert is the label with the correct spacing)
So what would be a good algorithm be to keep the label spacing consistent with everything else?
来源:https://stackoverflow.com/questions/54684014/finding-the-whitespace-algorithm-for-a-tentative-size-ascii-art-program