The third program is similar to the second one. It's about a business that needs a report generated. This time the business is a lawn care service and the report is about one customer. The program collects data from a user. It asks for the customer's name, address, and phone number. It asks how many years that customer has had an account with the company, and it asks about their yard -- its length and width, how many flower beds the customer has, and how many shrubs.
The difference between the third program and the second is that we now know how to create classes (and objects, which are just variables of that class type) to help solve such problems. So now instead of keeping all the data inside the main method, I'll read the data from the user and then stash all the data inside a new object. I'll be able to later get the data out of that object whenever and wherever I need it.
It seems sort of silly right now to make a new object for the data when all I have is one customer and that one customer's data is already in main. But imagine that I have 10 customers or 100 customers. Soon we're going to learn about writing loops. I could run a loop a bunch of times and each time collect data about one customer, then put all that customer's data in an object. We're also going to learn about containers that can hold multiple objects. I could declare a container of customers and put all of my customer objects into a container. All that is down the road...
Here is how I will structure my program. I'll have main do this:
- Read in all the data about a customer.
- Declare a new customer object and pass the data to the constructor of the customer class.
- Read in all the data about that customer's yard.
- Declare a new yard object and pass the data to the constructor of the yard class.
- Calculate the charge for that customer's yard. When I need some piece of data I'll use an accessor method on the appropriate object.
- Print out the report.
I'll put my main in a class file that will be called something like "TestLawnService" or "MyLawnService" or some such thing. The only thing in this class will be my main. I'll need two more files, one for my customer class and one for my yard class.
One thing you might find useful is printing a percent as a whole number with a percent sign. Once you learn about the DecimalFormat class in chapter 4, it will become easy. But you can do it with printf, too. Suppose my percent variable contains a real number between 0 and 100, such as 45.678. I can print this as 46% with this printf statement:
printf("The percentage is %.0f%%.", percentage);
The %.0f is a placeholder that says to round the corresponding value to a whole number. The %% is a placeholder that turns into the % character.
Program 3 was easier than program 2 for me because I already understood something about programs that read data and make a report.
No comments:
Post a Comment