26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7 Arrays 323<br />

15 // add each element's value <strong>to</strong> <strong>to</strong>tal<br />

16 for ( int counter = 0; counter < array.length; counter++ )<br />

17 <strong>to</strong>tal += array[ counter ];<br />

18<br />

19 JOptionPane.showMessageDialog( null,<br />

20 "Total of array elements: " + <strong>to</strong>tal,<br />

21 "Sum the Elements of an Array",<br />

22 JOptionPane.INFORMATION_MESSAGE );<br />

23<br />

24 System.exit( 0 );<br />

25 }<br />

26 }<br />

Fig. Fig. 7.6 7.6 Computing the sum of the elements of an array (part 2 of 2).<br />

7.4.5 Using His<strong>to</strong>grams <strong>to</strong> Display Array Data Graphically<br />

Many programs present data <strong>to</strong> users in a graphical manner. For example, numeric values<br />

are often displayed as bars in a bar chart. In such a chart, longer bars represent larger numeric<br />

values. One simple way <strong>to</strong> display numeric data graphically is with a his<strong>to</strong>gram that<br />

shows each numeric value as a bar of asterisks (*).<br />

Our next application (Fig. 7.7) reads numbers from an array and graphs the information<br />

in the form of a bar chart (or his<strong>to</strong>gram). The program displays each number followed<br />

by a bar consisting of that many asterisks. The nested for loop (lines 17–24) appends the<br />

bars <strong>to</strong> the String that will be displayed in JTextArea outputArea on a message<br />

dialog. Note the loop continuation condition of the inner for structure at line 22<br />

(stars

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!