Monday, September 22, 2008

Testing, testing, 1, 2, 3

Homework for today is to read pages 105-110 in your text. We're starting what are called conditional control structures. This is the feature of the language that allows your program to make choices based on certain data. It's what allows your program to be responsive to input from outside itself.



OK. I tried to introduce number formatting using the NumberFormat class and confused the whatchamacallit out of you - for which I apologize. We'll go over it again at the top of tomorrow's class but here's some background.

I said that in order to use NumberFormat we needed to declare a NumberFormat object and I gave an example of such a declaration:
NumberFormat myFormattingObj = NumberFormat.getInstance();

The line of code above creates a new NumberFormat object called myFormattingObj.

I hesitated when saying that because I realized that it contradicted what I had previously told you (and what you'd just practiced in the test) about declaring new objects in Java. Marya picked up on in it right away. Shouldn't it be something like NumberFormat myFormattingObj = new NumberFormat();, she asked?

So, it turns out that there is special type of method in Java called factory methods whose particular job is to instantiate objects. (If you have 10 minutes at some point I can explain why it's a good thing to have such a special type.) The getInstance() method of the NumberFormat class is such a factory method. All it does is return a new object. Effectively, you could replace NumberFormatNumberFormat.getInstance(); in the declaration above with new NumberFormat(); For our purposes (and to the best of my understanding) it does exactly the same thing.



Aside from the mechanics of declaring an object using a factory method, it's probably confusing that you're declaring an object to do number formatting at all.

Think of myFormattingObject as like a small custom body shop or garage that you declare to do some work on your numbers.

First you create the body shop: NumberFormat myFormattingObj = NumberFormat.getInstance():

Then you tell the body shop how you want to customize your number: myFormattingObj.setMaximumFractionDigits(3);

This says to set the maximum number of digits to display to be 3.

Then you submit your number to the body shop to have the work done on it: myFormattingObj.format(numWithDecimal);

If your number was 5.678948, then the result of the the last bit of code would be 5.679.

No comments: