In the previous page (loop from A to Z), you saw that you could true the characters. This page will explain how to create different models in Java by looping and printing characters. I will show in this tutorial how to print a pyramid of characters From “A” to “Z”.
The idea for this project is to get 5 á 6 methods, let’s say you want a pyramid of 15 lines:
- The first method will be your start method. You sketch a plan in the start method:
-
- you want a loop that goes from 1 – 15
- then you have to make a method to let Java/Eclipse know what you want per line. It is not necessary to make a new method but I will do that because you have a better structure and view. We call the (optional) method: printingPerLine. Now, you start method will look like this:
-
-
You see that your start method contains the loop (for-loop), you loop through every line and then the method printingPerLine will plan what to do every line.
-
- The second method printingPerLine has to contain 4 elements/methods per row
- Calculate the number of spaces
- Calculate the number of letters
- Compute the letter
- Printing method
- For the method printingPerLine, first, we have to know, how the print method is working. We want a loop that print the desired characters.
So, we got as input a character and the number of times the character has to be print. (As you can see, the loop will play the number of times the character has to be printed.)
Now we can create the printingPerLine method. Like I mentioned before, we will first write the line, in which we print the number of spaces. The second line will be the number of letters per line. We also create a line which sets us to the next row ( out.print(“/n”) ).
- The fourth method, will be the method in which you calculate how many spaces you got in one line and return the number of spaces.
- The fifth method will be the method in which you calculate how many letters you got in one line and return the number of letters.
- The sixth method will be the method in which you calculate how many letters you got in one line and compute the letter you want to print.
When you delete the ” + i”, the method will only print A. And you will get this result:
The return line, returns the values to the method printingPerLine. Then it will be sent to the method which prints everything. The result is the first pyramid.
The whole program is:
output: