Course Description
Syllabus
Reading List
Team Project
|
Exercise 2
Last modified: September 8, 8:10 pm
This exercise should take about 3-4 hours to complete. You will
write simple Java programs that demonstrate:
- Three basic control structures (sequential, conditional,
iterative)
- Defining and instantiating a Book class and using a method
- Arrays
Once you have completed this exercise, you should be ready to combine
these elements to create more complex programs.
The easiest way to start will be to launch Eclipse. Use the File menu
to create a new project; call it Exercise 2. Then create a new class
called Exercise and ensure that the checkbox for "public static void
main (String args[])" is selected. Then add a single statement inside
the main method of the Exercise class that prints out "Hello World!"
and run the program. This is exactly what you did in Exercise 1, so
if you have trouble getting this far you should review the tutorial in
exercise 1. You'll do something like this every time you start a new
project, so be sure you are comfortable getting this far so that you
can focus your attention on what you're really trying to learn.
Sequential execution
Now all you need to do is change that one statement to be a sequence
of two statements. Just add a second statement under the first that
prints out "Goodbye Cruel World!" and run your program again. This
demonstrates the sequential control structure; Java system simply
executes your statements in the order that they appear in your
program.
Conditional execution
Okay, next we'll demonstrate conditional execution. Let's change the
program so that it will print one or the other of those, but not
both. First, define a boolean variable called "optimist" and set its
value to "true". You can do this by adding a line at the top of the
main class that says "boolean optimist=true;". Next, use an if
statement to choose which of the two print statements will be
executed. The syntax for an if statement is "if ( ... )
... else ... ;" where the first "..." is a boolean expression (i.e.,
something that works out to "true" or "false"), the second "..." is a
statement that is executed when the boolean expression is true, and
the third "..." is executed when the boolean expression is false. It
does not matter whether everything is on the same line or not. Set up
your if statement so that "Hello World!" is printed when
optimist is true and run your program to be sure that's what gets
printed. Then change the program to make optimist false, and run it
again to ensure that just by making that single change you have caused
the program to print "Goodbye Cruel World!". If so, you have mastered
conditional execution!
Iterative execution
Okay, now for the third one, iterative execution (also called
looping).
Lets modify the program again so that it
does whatever it is going to do 5 times. The control structure to do
this is the for statement, which has the syntax "for (int i=0;
i<5; i++) { ... }". Again, it does not matter whether this all
appears on the same line. Put a for statement outside your
if statement (in other words, make the "..." in the for
statement the entire contents of your main method except the
declaration of "optimist" (which should now be setting optimist to
false, after finishing the demonstration of the conditional
statement). Now run you program; it should print "Goodbye Cruel
World!" five times, on five lines. If it does, you've demonstrated
the iterative statement!
A note on Strings
Strings in Java are actually classes, not primitive variables
like int, boolean, and float. That is why when you instantiate them
you use the new String() construct. There is a shortcut if you
are assigning a literal (hardcoded) value. These two statements
both create a String variable (myName) and assign it a value (Bill):
String myName = new String("Bill");
String myName = "Bill";
More information about Strings can be found at http://java.sun.com/docs/books/tutorial/java/data/strings.html.
Defining a Book class
Next you are going to create a class to model books. As you do this,
you will build on use the material from the Sept 7 class. Your Book
class will have instance variables for title, author, copyright
year, and price. It will also have a method (called
displayBook() to display the Book's information. You will
then create a tester class with a main() method that
instantiates (creates) several Book objects, assigns values to the
instance variables, and calls the displayBook() for each
instance.
Start building your Book class by looking at the Dog class on page
36 of Head First Java. Notice that the instance variables are declared
at the top, outside of any methods. The title and author
instance variables are Strings. The copyrightYear is an integer
(int). And just to be adventurous, price is a floating point number
(float).
The displayBook() is similar to the Dog's
bark(). But you will print the four variables instead of
"Ruff! Ruff!". Remember how we concatenated strings with the plus
(+) operator in class:
System.out.println ("Hello World " + counter);
Use the same approach to display the variables.
Notice that your Book class doesn't have a main() method.
That will be in the BookTestDrive class that you will create next.
Declare a book object variable called book1. Remember that because
you are creating an object, you have to use the new Book().
construct. Next, set it's instance variables to reflect your favorite
book. Remember that you have to use the dot operator. For example, to
assign a value to the title variable for the book1 object:
book1.title = "Head First Java";
Then call its displayBook() method, again using the dot
operator. You can look at the Movie example on page 37.
A note on Arrays
An Array in Java is a special kind of class. The most obvious special
thing is that it uses square brackets, in several ways. You use the
square brackets when declaring an Array variable so the compiler knows
that it is an Array. For example, to declare an Array of ints:
int [] nums;
This tells the Java compiler that you have an Array, but it
doesn't instantiate (create) an object.
Since it is a
class, you have to instantiate it with the new keyword.
You use square brackets with a number inside them to indicate the
length of the Array.
nums = new int[5];
This creates an array of five integers. To reference an element
of the Array, you use the square brackets again. You can
use a literal number, e.g.:
System.out.println (nums[3]);
You can also use a variable or an expression, like we did in class:
System.out.println (days[counter]);
Remember that Arrays in Java are "zero based", which means the first
element has index 0 (e.g. nums[0]). So the second element is nums[1],
the third is nums[2], and so on.
More information about Arrays can be found at
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html.
An Array of Books
The last part of this exercise is to create an array of 4 Books,
then loop through the array to display the info about all of them.
You don't need to change Book class, just the BookTestDrive class.
Replace your book1 and book2 variables with an Array called books
with 5 elements:
Book [] books;
books = new Book[5];
You can assign values to each book by using the square brackets
to identify the specific Book and the dot operator to identify the
variable. For example, to set the title of the 3rd book:
books[2].title = "Head First Java";
Finally use a for or while loop to iterate over the entire
Array and display each book.
If you have problems...
But what if you got stuck somewhere? That's actually not bad -- the
reason that you do exercises like this is to learn what you know and
what you don't know. Obviously, you'll want to try to get unstuck by
backing up and trying to figure out what it is you don't understand.
If your problem is with Eclipse, run the tutorial again and see if you
can figure out how to get it to do what you want. If your problem is
with Java, maybe your problem is as simple as a typing mistake -- try
typing in and running a few examples from the text (Head First Java)
before trying to write your own programs. Next, try to find examples
that contain parts that look like what you are trying to do, and see
if you can understand how they are doing it; copying snippets of
working code is not a sin in programming -- it is often a good idea
that can save you a lot of work. The creativity comes in how you put
things together.
So what do you do if it still is not working? Send a question to
the TA or to me by email. We might be able to help if you can
describe what you tried well enough for us to duplicate the problem;
if you include your code, this will be much easier for us. What if we
can't help? Then you get to the real purpose of this assignment --
bring your question to class. Listening in class is useful, but it
has nowhere near the value for learning that asking questions does.
So the real purpose of this exercise is to help you to know what
questions you should be asking.
One final word of advice. Don't spend more than two hours on this; it
is not a hard assignment. Indeed, you will do something very much
like this during the final exam, and you will do it then in the first
5 minutes of the exam because it will not be the main point of what
you will be demonstrating then -- these are simply the skills that
you need any time you write a program in Java using Eclipse. But if
you get stuck somewhere and can't get unstuck on your own, you could
waste a lot of time running down blind alleys. So give this a couple
of hours, and if you're still struggling with it, put it aside and
bring your questions to class.
Bill Kules
|