CS-151 Labs > Lab 1. The First Cup of Java
Part 1. Pyramids revisited
Add a new Java class to your project. This time, use lab1
as the package name. Use Pyramid
as the name of the class and check the button for including a
public static void main
stub.
For your first more serious program, we want you to create a class called Pyramid that draws
a simple 2D pyramid out of *
characters. Your program will:
- Check that the user has entered exactly 1 command-line argument. To do
this, use the String array parameter to main called
args
, and check thatargs.length
is equal to 1. If it isn’t, you should print a message to the user and then quit by callingSystem.exit(1)
; -
Convert the command line argument to an integer.
Integer.parseInt()
is a static method in the Integer class that allows you to convert a String that represents a number and turn it into an int. Convert the first argumentargs[0]
into an int that represents the number of rows in your pyramid.int height = Integer.parseInt(args[0]);
- Print out the pyramid
Here are some examples of inputs and outputs. (Recall from the
Lab 0 that the way you provide command line arguments in Eclipse is from
the Run As
> Run Configurations…
menu option and then click on the Arguments
tab.)
input: 5
output:
*
***
*****
*******
*********
input: 1
output:
*
No input
output:
To run: java Pyramid <number>
You may want to spend a couple of minutes figuring out how many stars and how many spaces you would need to print on each line as a function of height and loop iteration variable.