For your first program, you will create a Java program that draws a pyramid out of *
characters that has a height determined by the user. This will practice using for
loops, System.out.print
and System.out.println
statements, and getting input from the user through the command line.
For example, if the user wants a pyramid of height 5, a run of your program like:
java Pyramid 5
should create output that looks like:
User input: 5
Pyramid:
*
***
*****
*******
*********
If the user only wants a pyramid of height 1, your program’s output should look like:
User Input: 1
Pyramid:
*
Notice that each line is progressively wider (adding two more *
compared to the previous row) and the stars are centered based on the widest row at the bottom.
Inside your GitHub repository, you will find a file called Pyramids.java
. Open this file in Visual Studio Code by either using the “File” > “Open” dialog box, or double click on the Pyramids.java
file on the left side of your IDE in the “Explorer” area. The skeleton of the program is already provided for you in this file. All you need to do is implement the program in the public static void main(String[] args)
function.
The flow of your program should be:
if
statement and the value of args.length
. If there is not exactly one command line argument, then you should print a message to the user letting them know what went wrong and gracefully close the program by calling System.exit(-1)
; In that case, your program might look like the following:User Input: Missing
You need to provide the number of rows of the pyramid as a command line argument. Please try again.
Integer.parseInt(String s)
function is a built-in method of the Integer
class that allows you to convert a String
into an int
. In this program, args[0]
is the String
that contains the first command line argument supplied by the user.int height = Integer.parseInt(args[0]);
Remind the user of their inputted value by printing it back to them with a heading explaining what is being printed (e.g., input: 5
)
Print out the pyramid following the pattern displayed at the top of this webpage. You may want to spend a couple of minutes figuring out how many stars and how many spaces you will print in each line as a function of height and your loop index.
In your terminal window, type:
javac Pyramid.java
java Pyramid
To compile and run your program.
Once you’ve finished your program, don’t forget to add
and commit
your changes to git, then push
them to your GitHub repository. Instructions for how to do so can be found earlier in the Warmup.