How to Make a Pattern of Asterisks in Java
Although Java has the capacity to create complex drawings and render detailed images, beginning programmers can create their own simple graphics using ASCII art. Creating ASCII patterns to make, for example, a pyramid shape using asterisks in Java only requires a few lines of code and some clever loops. In order to create patterns, you will use two of Java's output methods. System.out.print(String output) prints whatever is enclosed in the parentheses to the program's output line. System.out.println(String output) prints the contents of the parentheses and then moves to the next line of output.
Instructions
-
-
1
Create a new project in your integrated development environment, or IDE, of choice. Place your cursor inside of the main method.
-
2
Enter the following code to define the number of rows in the pyramid:
"int totalHeight = 8;"
Replace the number 8 with your desired number of rows. -
-
3
Enter the following code to create a loop that will define the number of rows in your pattern:
"for(int i = 0; i < totalHeight; i++){}"
-
4
Place your cursor on the line in between the two brackets and enter the following code to create a subloop that will insert the necessary spacing before the first asterisk in each row:
"for(int j = i+totalHeight; j<totalHeight*2; j++){
System.out.print("_");
}"
On each row, this loop will add two underscores for every row you are away from the bottom. -
5
Create a new subloop to insert the correct number of asterisks on each row. Insert the following code inside of the first loop, below the closing bracket of the first subloop:
"for(int k = 0; k < i;k++){
System.out.print("*_");
}"
This code will insert an asterisk and an underscore for each row you are down from the first row. It will not insert anything on the first row because an extra underscore after the final asterisk on each row would upset the pattern. -
6
Add a new line of code to add the final asterisk on each row. Insert this code just below the closing bracket of the second subloop:
"System.out.print("*");" -
7
Add a final subloop to insert the proper spacing on the far side of the pyramid. Insert this just inside of the main loop's closing bracket:
"for(int j = i+totalHeight; j<totalHeight*2;j++){
System.out.print("_");
}" -
8
Call "System.out.println()" to finish the current line of output and move on to the next line in the pyramid. Insert this code after the final subloop but still inside of the main loop's closing bracket:
"System.out.println();" -
9
Run your program. It should produce the following output:
"________*________
_______*_*_______
______*_*_*______
_____*_*_*_*_____
____*_*_*_*_*____
___*_*_*_*_*_*___
__*_*_*_*_*_*_*__
_*_*_*_*_*_*_*_*_"
-
1
Tips & Warnings
Experiment with different kinds of nested loops and different loop parameters to create new patterns.
Do not include the opening or closing quotation marks in your code.