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.

360 Arrays Chapter 7<br />

Fig. Fig. 7.26 7.26 The 36 possible outcomes of rolling two dice.<br />

roll the dice 36,000 times. Use a single-subscripted array <strong>to</strong> tally the numbers of times each possible<br />

sum appears. Display the results in a JTextArea in tabular format. Also, determine whether the <strong>to</strong>tals<br />

are reasonable (i.e., there are six ways <strong>to</strong> roll a 7, so approximately one sixth of all the rolls should<br />

be 7). The applet should use the GUI techniques introduced in Chapter 6. Provide a JBut<strong>to</strong>n <strong>to</strong> allow<br />

the user of the applet <strong>to</strong> roll the dice another 36,000 times. The applet should reset the elements<br />

of the single-subscripted array <strong>to</strong> 0 before rolling the dice again.<br />

7.16 What does the program of Fig. 7.27 do?<br />

1 // Exercise 7.16: WhatDoesThisDo.java<br />

2<br />

3 // <strong>Java</strong> core packages<br />

4 import java.awt.*;<br />

5<br />

6 // <strong>Java</strong> extension packages<br />

7 import javax.swing.*;<br />

8<br />

9 public class WhatDoesThisDo extends JApplet {<br />

10 int result;<br />

11<br />

12 public void init()<br />

13 {<br />

14 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };<br />

15<br />

16 result = whatIsThis( array, array.length );<br />

17<br />

18 Container container = getContentPane();<br />

19 JTextArea output = new JTextArea();<br />

20 output.setText( "Result is: " + result );<br />

21 container.add( output );<br />

22 }<br />

23<br />

24 public int whatIsThis( int array2[], int size )<br />

25 {<br />

26 if ( size == 1 )<br />

27 return array2[ 0 ];<br />

Fig. Fig. 7.27 7.27 Determine what this program does.<br />

1<br />

2<br />

3<br />

4<br />

5<br />

6<br />

1 2 3 4 5 6<br />

2<br />

3<br />

4<br />

5<br />

3<br />

4<br />

5<br />

6<br />

4<br />

5<br />

6<br />

7<br />

6 7 8<br />

7<br />

8<br />

9<br />

5<br />

6<br />

7<br />

8<br />

10<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01<br />

6<br />

7<br />

8<br />

9<br />

7<br />

8<br />

9<br />

10<br />

9 10 11<br />

11 12

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

Saved successfully!

Ooh no, something went wrong!