Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

518 Part II: The Java Library


for(int x=0; x<10; x++, t += 0.5)
if(val < t) {
bell[x]++;
break;
}
}
System.out.println("Average of values: " +
(sum/100));

// display bell curve, sideways
for(int i=0; i<10; i++) {
for(int x=bell[i]; x>0; x--)
System.out.print("*");
System.out.println();
}
}
}

Here is a sample program run. As you can see, a bell-like distribution of numbers is obtained.

Average of values: 0.0702235271133344
**
*******
******
***************
******************
*****************
*************
**********
********
***

Observable


TheObservableclass is used to create subclasses that other parts of your program can
observe. When an object of such a subclass undergoes a change, observing classes are
notified. Observing classes must implement theObserverinterface, which defines the
update( )method. Theupdate( )method is called when an observer is notified of a change
in an observed object.
Observabledefines the methods shown in Table 18-7. An object that is being observed
must follow two simple rules. First, if it has changed, it must callsetChanged( ). Second,
when it is ready to notify observers of this change, it must callnotifyObservers( ). This
causes theupdate( )method in the observing object(s) to be called. Be careful—if the object
callsnotifyObservers( )without having previously calledsetChanged( ), no action will take
place. The observed object must call bothsetChanged( )andnotifyObservers( )before
update( )will be called.
Notice thatnotifyObservers( )has two forms: one that takes an argument and one that does
not. If you callnotifyObservers( )with an argument, this object is passed to the observer ’s
update( )method as its second parameter. Otherwise,nullis passed toupdate( ). You can use
the second parameter for passing any type of object that is appropriate for your application.
Free download pdf