RoboDuke's School of Java - Lesson 4, Chapter 5

So---are you ready for more Java?? If you have forgotten (how could you?? You had better not – it will be on the quiz!!) I am RoboDuke, the Javarian. We finally are putting a lot of the ideas together and developing programs that have some substance. In this lesson, we will review the constructs that we actually have been using in our programs already (you cannot develop a significant application without them) and will look at extra-strength methods. We will also discuss how to use solid design in your program development so that your Robot-friends will not laugh at your coding. First – a warning. If you see any of these dialog boxes pop up during lesson 4, DO NOT --- I repeat DO NOT contact me! I may be a Javarian but I cannot perform miracles!!!
Warning 1

Error 2Error 2

Now --- on to our lesson! Download our jar file for lesson 4 from the link below:

Let’s look first at the package named answerslesson3. The movie to watch explaining these answers is at

The code is filled in for the and programs. Yours should be similar. Note the two different versions for the netCost() method (remember --- this is called overloading).

public double netCost(double value, double sfee)
return value - sfee;

public double netCost()
return cost() - storageFee();

Which do you think is better? The Robot communities (and most Java programmers) prefer the second one. By using this version, you are guaranteed that you have the latest values for the cost and storage fees by doing the calculation right in the netCost() method. Also - you also are not relying on the person who wrote the driver program to correctly pass in the parameter values. But both work fine. In the driver program, I changed the call for the Scanner class method next() to nextLine() to avoid the problem that would occur if the crop name had more than one word in it. Also note the loop that was added. We will (finally!!!) be discussing such constructs in this lesson.

Now let’s look at the and application. Did you have any problems with this? The most common problem is to accidently copy and paste some of the code from the document outside of a method structure. Remember that in Java, all code except instance variable declarations must go inside of a method.

We are again letting Java assign the Widget numbers to insure that they are unique. In the Driver, do study the code for the find() method. This is a common algorithm that is needed. Often you want to search for an item. You need to look through the collection until one of two things happen: 1) you find it or 2) you get to the end of the collection. The line

while (!found &&location

takes care of that. We also want to make certain that we indicate to the user if the item was not found (i.e. we get to the end of the loop and the variable found still equals false).

So how did you do with selling Robots? The dull version of the driver is pretty useless! It only works for three robots being stored in two retail stores. The code has to be rewritten every time you add a robot and/or a store. Not good reuse of code!! The cool version is so much better and flexible. It can be used for any number of robots in any number of stores. It also stores the information in an array. The advantage (if you have not yet figured this out about arrays) is that when the loop that collects data is finished, we still have all of the data stored in the array so we could do such things as printing the results alphabetically, adding a total, or finding out which robot had the maximum number of sales. Collections are a wonderful thing!!! And later we will find ones that are even cooler than arrays!!!

Is this the best version we can make for selling the robots? One thing we lost was the ability to maintain information about how many robots of each type were sold in each of the stores. We have an instance variable for the total number of robots sold, but not the number sold in each store.

RoboDuke’s Extra Strength Challenge

See if you can alter this example to keep track of how many robots were sold for each type of robot in each of the individual store!!! Maybe keep the store name also? Assume different robots can be sold in different sets of stores (ex. RoboPets are sold in BestBuy in San Diego and Target in Phoenix but Robosapiens are sold only in Walmart in Seattle). Send your answer to and impress her. Tell her RoboDuke sent you!!! She will post the best answers and you can become famous!!!

That was a tough Extra Strength Challenge---but I created a real cool answer I will post in the next lesson. In the meantime – send your answers to her.

So guess that it is time for a RoboDuke nap. Zzzzzzzzzzzzzzzzzzzzzzzzzz.

On to chapter 5. But before we do, talk to some old computer programmers if you know any and listen to their tales of “When I first was programming….”. They will tell you the stories of what life was like before IDEs (the integrated development environments). With Eclipse people get use to opening up the IDE, going to the editor and then they just start typing away. No planning ahead. No diagramming. No nothing. If an error occurs, the IDE tells you right away!! All compile-time errors are removed by fixing and fixing until the red Xs are gone. (Boy! I want to smack those robot-programmers that just throw in more and more braces because the error message was “un-matching braces” --- without them even considering where they should go and why). And often the feeling is that as long as the results show up with no run-time errors, it must be a killer-great program!!! Unfortunately, programming this way creates poor code structures and hard-to-maintainable applications.

It was never like this for the old timers. (Find one who will tell you stories of punch cards and 24 hour turnaround times on submissions to the mainframes). Slow and painful but make for great programmers since careful planning was imperative.

The pass rate on the Sun Java certification exam is low mostly for this reason. The questions are not hard ---it is just that most of the questions involve code fragments with the choice of answers like: a) compile-time error will occur b) run-time error will occur c) a certain output pattern d) a different output pattern. And programmers become too use to using IDEs that immediately flag all of their errors. They therefore have a lot of difficulties with recognizing the first two error types by just looking at the code on the test site without the aid of their handy dandy IDE.

Chapter 5 discusses how to correctly design an application starting with high-level design. Note the flow chart on page 97 of your text. These were the heart of program development in the “old days”. We still use them today---but they are really only useful for a single class and overall concepts of the application as a whole. We will show you something later called UML (universal modeling language) diagrams that are much more useful for the application as a whole.

This is not meant to say that flow charts are not useful. A single picture is worth a thousand words (You didn’t know that RoboDuke was a philosopher, did you?). The flow chart on page 97 really shows in a nutshell what the program needs to do and how to do it. It also shows how to diagram the constructs that we will discuss in this lesson. I will wait here while you study this and absorb the information about the application that we need to write………………………………………………..

This chapter is chock full of good advice!! Read it carefully more than once!!! I will even repeat the steps that they list for developing a class from page 99.
a. Figure out what the class is suppose to do
b. List the instance variables and methods
c. Write prep code for the methods
d. Write test code for the methods
e. Implement the class
f. Test the methods
g. Test the application on live users

Remember: Prep code => Test code => Real code

Not much more a little robot like me can say about program development. Especially since the authors of your text are Sun employees in one form or another---and super great programmers. Their advice is solid and to be successful, you need to follow it!

Follow through the example in the book and type in the code from scratch as they develop it. By the time you get to the end of the chapter, you should have a super wonderful application that was developed with solid design principles in mind.

So—on to constructs! We have been using these all along in the previous modules since you cannot write any type of significant program without them. In Java, programs start by executing the main() method one line at a time and typically ends when the main() method ends. But there are three types of constructs that can alter this line-by-line top-to-bottom execution and these are:
a. Loops
b. Decisions
c. Method calls (either in the same class or from instances of another class)

We have already looked at the third one in the list. So for this lesson, we will concentrate on the first two. Loops are when you execute a set of code over and over until some condition changes. Decisions are when you make a choice of which set of code to execute based on a condition but only execute it once.

Most programming languages have at least one choice for each of these constructs but Java provides a number of options for each.

Loops – do/while, while, and for loops (three choices)
Decisions - if, if/else, and switch statements (three choices)

We have used many of these in the first three lessons. Go back and look at these examples to see the wide variety of uses.

Each type of construct is based on a condition. A condition (which is always placed in a set of parentheses) is a statement that evaluates to true or false. If the condition evaluates to true, the code following it is executed. If the condition evaluates to false, the code following it is skipped and the program continues after the area where the following code is located. Typically, the “following code” is written in a set of { } braces. The “following code” is executed once if it is a decision and repeatedly if it is a loop.

Let’s look at some examples in concept before we look at them in code. Let’s consider a loop and loop for the condition “while RoboDuke has more than one million dollars”. (Didn’t know I was a rich little robot, did you?) The code that is located in parenthesis will be executed once ---then it will be checked to see if RoboDuke still has more than one million dollars and if so, will be executed again ---and it will be checked to see if RoboDuke still has more than one million dollars and if so, it will be executed again-----over and over and over until the time that RoboDuke no longer has over one million dollars (sad!!). At that point, the program will not necessarily end --- but will drop out of the loop and continue after the statements that are in parentheses.

Using the textbook’s idea of prep code:

RoboDuke has $4,400,000
While (RoboDuke has over $1,000,000)
RoboDuke buys a pizza for $10.00
RoboDuke spends $499,990 on a video game
// the program only gets here after RoboDuke’s
//net income is $1,000,000 or less

RoboDuke eats his pizzas!!!

So---the question becomes------how many times does the loop execute? How many pizzas does RoboDuke eat after the loop ends? And the real question is ---what kind of video game costs that much???

Anyhow, RoboDuke starts with $4,400,000 which is over $1,000,000. So the code executes. He buys a pizza and a video game—so a total of $500,000 is subtracted from his income. He now has $3,900,000 (which is still greater than $1,000,000 so the loop continues). So he again spends $500,000 on pizza and a video game, and now he now has $3,400,000 (which is still greater than $1,000,000 so the loop continues). So he again spends $500,000 on a video game and a pizza so he now has $2,900,000 (which is still greater than $1,000,000 so the loop continues).

The concern is whether the loop will ever end! In some cases, if you do not devise the code correctly, you may end with an infinite loop and the program will never end. Consider the case that he sells a video game for $500,010 instead of him buying them. He starts with $4,400,000 and gains $500,000 each loop (remember he bought a pizza) – so he will never get under one million dollars. He will continue to collect pizzas but never get to the point where he can eat them). In this case we have an infinite loop. And he will die of starvation ---but be very rich when he does so! We hope that this is not the case.

In our program, the correct answer is that he will probably get fat because he will end up eating seven pizzas! He will finally get to eat them since the loop ends and the lines after the loop do get executed so he can eat the pizzas.

If we change this to a decision, the code only executes once if the condition is true. Assume that we, instead, write:

RoboDuke has a variable amount of money to start with
If (RoboDuke has over $1,000,000)
RoboDuke buys a pizza for $10.00
RoboDuke spends $499,990 on a video game
// the program always gets here---it has only been checked
//once to see if RoboDuke’s income
// is greater than $1,000,000. Therefore – he either
//has one or no pizzas to eat in the next line

RoboDuke eats his pizzas!!!

In this case, he gets to eat only one pizza if he is originally worth over a million dollars---otherwise he starves to death!

If we change this to an if/else we get

RoboDuke has a variable amount of money to start with
If (RoboDuke has over $1,000,000)
RoboDuke buys a pizza for $10.00
RoboDuke spends $499,990 on a video game
RoboDuke is donated some slop to eat
// the program always gets here---it has only been checked once to see if
// RoboDuke’s income is greater than $1,000,000.

RoboDuke eats what he received!!!

In this case, he gets to eat only one pizza if he is originally worth over a million dollars --- otherwise he eats slop! (At least he did not starve to death!!).

Let’s look at some actual coding. Remember to review all of the code where we have used these types of loops and decisions from the past lessons first. Open the package named lesson4 in the current jar file. You will find examples of each type of construct here. Work through the code and read the comments for each. Keep these for reference when you begin to construct your own loops and decisions.

You might ask about how to find bugs in your program (not that any of you Robots out there would make any errors!!!). Eclipse has a very nice debugging tool and the sooner that you learn to use it, the faster you will find your errors in your coding. But do not use it or start any coding until you have followed the design principles from this text!!!!

Now It’s Your Turn

Write a program used to determine the smartest robot. Input from the keyboard will be the robot’s name and the robot’s IQ score. You do not know how many robots that the user will enter from the keyboard (this should clue you in on what type of loop to use). The loop ends when the user types in END for the robot’s name. After all robots are entered, have the program display the name and IQ for the robot with the highest IQ score.

Now It’s Your Turn

Rewrite the program to use if/else constructs instead of the switch construct. Get the month and year from a Keyboard entry and add a loop that will do it more than once (you can choose what the user will enter to end the loop).

Java Quick Tip:  Look at the Quick Tip on Constructs


Java Quick Tip:  Look at the Quick Tip on Debugging in Eclipse