1. Trang chủ
  2. » Công Nghệ Thông Tin

giáo trình Java By Example phần 7 docx

52 320 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 52
Dung lượng 127,54 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Youcan even create an array for a set of objects like the TextField objects Applet16 uses to get bowlingscores from the user.. For example, the long way to initialize the arrays without

Trang 1

import java.awt.*;

import java.applet.*;

public class Applet16 extends Applet

{

TextField textField1, textField2, textField3;

int avg1, avg2, avg3;

public void init()

{

textField1 = new TextField(5);

textField2 = new TextField(5);

textField3 = new TextField(5);

Trang 2

When you run Applet16, you can enter bowling scores into the three boxes at the top of the applet's

display area After you enter these averages, they're displayed on-screen as well as copied into the threevariables avg1, avg2, and avg3

Nothing too tricky going on here, right?

Trang 3

Now examine the listing Remember in Chapter 10, "The while and do-while Loops," when youlearned to keep an eye out for repetitive program code? How about all those calls to getText(),

drawString(), and valueOf() in Listing 13.1? The only real difference between them is the

specific bowler's score that's being manipulated If you could find some way to make a loop out of thiscode, you could shorten the program significantly How about a for loop that counts from 1 to 3?

But how can you use a loop when you're stuck with three different variables? The answer is an array Anarray is a variable that can hold more than one value When you first studied variables, you learned that avariable is like a box in memory that holds a single value Now, if you take a bunch of these boxes andput them together, what do you have? You have an array For example, to store the bowling averages foryour three bowlers, you'd need an array that can hold three values You could call this array avg Youcan even create an array for a set of objects like the TextField objects Applet16 uses to get bowlingscores from the user You could call this array textField

Now you have an array called avg that can hold three bowling averages and an array called

textField that can hold three TextField objects But how can you retrieve each individual average

or object from the array? You do this by adding something called a subscript to the array's name A

subscript (also called an index) is a number that identifies the element of an array in which a value isstored For example, to refer to the first average in your avg array, you'd write avg[0] The subscript isthe number in square brackets In this case, you're referring to the first average in the array (array

subscripts always start from zero.) To refer to the second average, you'd write avg[1] The third average

is avg[2]

If you're a little confused, look at Figure 13.2, which shows how the avg[] array might look in

memory In this case, the three bowling averages are 145, 192, and 160 The value of avg[0] is 145,the value of avg[1] is 192, and the value of avg[2] is 160

Figure 13.2 : An array can hold many values of the same type.

Example: Creating an Array

Suppose that you need an array that can hold 30 floating-point numbers First, you'd declare the arraylike this:

Trang 4

numbers = new float[30];

The last step is to initialize the array, a task that you might perform using a for loop:

for (int x=0; x<30; ++x)

numbers[x] = (float)x;

These lines of Java source code initialize the numbers[] array to the numbers 0.0 to 29.0 Notice howthe loop only goes up to 29 This is because, although there are 30 elements in the numbers[] array,those elements are indexed starting with 0, rather than 1 That is, the subscript is always one less than thenumber of the element you're accessing The first element has a subscript of 0, the second a subscript of

1, the third a subscript of 2, and so on

Example: Using a Variable as a Subscript

As you learned in a previous chapter, most numerical literals in a Java program can be replaced by

numerical variables Suppose you were to use the variable x as the subscript for the array avg[] Then(based on the averages in Figure 13.2) if the value of x is 1, the value of avg[x] is 192 If the value of x

is 3, the value of avg[x] is 160

Now take one last, gigantic, intuitive leap (c'mon, you can do it) and think about using your subscriptvariable x as both the control variable in a for loop and the subscript for the avg[] and textFieldarrays If you use a for loop that counts from 0 to 2, you can handle all three averages with much lesscode than in the original program Listing 13.2 shows how this is done

Listing 13.2 Applet17.java: Using Arrays.

Trang 5

public void init()

{

textField = new TextField[3];

avg = new int[3];

Trang 6

Tell Java that the program uses classes in the awt package.

Tell Java that the program uses classes in the applet package

Derive the Applet17 class from Java's Applet class

Declare TextField and int arrays

Override the Applet class's init() method

Create the textField and int arrays with three elements each

Loop from 0 to 2

Create a new TextField object and store it in the array

Add the new TextField object to the applet

Set the new TextField object's text

Override the Applet class's paint() method

Display a line of text

Loop from 0 to 2

Get the text from the currently indexed TextField object

Draw the retrieve text on the applet's display area

Convert the value and store it in the integer array

Override the Applet object's action() method

Force Java to redraw the applet's display area

Tell Java everything went okay

At the beginning of Listing 13.2, you'll see a couple of strange new variable declarations that look likethis:

TextField textField[];

Trang 7

int avg[];

These declarations are much like other declarations you've seen, except both of the variable names endwith a set of square brackets The square brackets tell Java that you're declaring arrays rather than

conventional variables

Once you have the arrays declared, you must create them In Applet17, this is done like this:

textField = new TextField[3];

avg = new int[3];

Here you use the new operator to create the arrays To tell Java the type of arrays to create, you follownew with the data type and the size of the array in square brackets In other words, the first line abovecreates an array that can hold three TextField objects The second line creates an array that can holdthree integers

Once you have your arrays created, you can use a loop to reduce the amount of code needed to initializethe arrays For example, the long way to initialize the arrays (without using a loop) would look

something like Listing 13.3:

Listing 13.3 LST13_3.TXT: Initializing an Array without Looping.

textField[0] = new TextField(5);

Trang 8

As you learned, however, you can use a variable-specifically, a loop control variable-as the array

subscript That's what Applet17 does, which enables it to initialize the textField array as shown inListing 13.4

Listing 13.4 LST13_4.TXT: Initializing an Array Using a Loop.

element As you can see, using a loop with an array can greatly simplify handling a group of relatedvalues Imagine how many lines of source code you'd save if the array had 1,000 elements instead of onlythree To accommodate the larger array, you'd only have to change x<3 to x<1000 in the first line ofthe for loop

CAUTION

Be careful not to try accessing a nonexistent array element Forexample, in Listing 13.4, if you tried to access textField[3],you'd be beyond the boundaries of the array Java will generate anexception when this happens, which means your applet may or maynot perform the way you want it to (You'll learn more about

exceptions in Chapter 30, "Exceptions.")

The init() method isn't the only place Applet17 takes advantage of a loop to handle the program'sarrays In the paint() method, you can see the loop shown in Listing 13.5

Listing 13.5 LST13_5.TXT: The for Loop from the paint( ) Method.

for (int x=0; x<3; ++x)

Trang 9

This loop simplifies the printing of the bowlers' scores and the loading of the avg[] array with the

scores Again, imagine how much time and space you'd save if the arrays in question had thousands ofelements rather than only three It's at times like those that you really learn to appreciate arrays

NOTE

The memory locations that make up an array are called elements of

the array For example, in an array named numbers[],numbers[0] is the first element of the array, numbers[1] is thesecond element, and so on The reason numbers[0] is the firstelement of the array is because of the number 0 inside the subscript.It

is the number inside the subscript that defines which array location isbeing referred to

Multidimensional Arrays

So far, you've looked at simple arrays that hold their data in a list However, most programming

languages also support multidimensional arrays, which are more like tables than lists For example, take

a look at Figure 13.3 The first array in the figure is a one-dimensional array, which is like the arraysyou've used so far in this chapter The next type of array in the figure is two-dimensional, which workslike the typical spreadsheet type of table you're used to seeing

Figure 13.3 : Arrays can have more than one dimension.

Although Java doesn't support multidimensional arrays in the conventional sense, it does enable you tocreate arrays of arrays, which amount to the same thing For example, to create a two-dimensional array

of integers like the second array in Figure 13.3, you might use a line of code like this:

int table[][] = new int[4][4];

This line of Java code creates a table that can store 16 values-four across and four down The first

subscript selects the column and the second selects the row To initialize such an array with values, youmight use the lines shown in Listing 13.6, which would give you the array shown in Figure 13.4

Trang 10

Figure 13.4 : Here's the two-dimensional array as initialized in Listing 13.6.

Listing 13.6 LST13_6.TXT: Initializing a Two-Dimensional Array.

You refer to a value stored in a two-dimensional array by using subscripts for both the column and row

in which the value you want is stored For example, to retrieve the value 11 from the table[][] arrayshown in Figure 13.4, you use a line like this:

int value = table[3][2];

Trang 11

A quick way to initialize a two-dimensional array is to use nested for loops, as shown in Listing 13.7.

Listing 13.7 LST13_11.TXT: Using Loops to Initialize a Two-Dimensional Array.

initializes an element of the array Because x and y both equal 0, the array element table[0][0] getsset to 5 Then the inside loop sets y to 1, which means table[0][1] gets set to 5 When the inner loopfinishes, the program branches back to the outer loop, setting x to 1 The inner loop repeats again, onlythis time with x equal to 1 and y going from 0 to 2 Finally, when both loops finish, the entire array isinitialized

Of course, to create the array shown in Figure 13.4 with loops, you have to be a little more tricky, asshown in Listing 13.8 Work through each loop to see how the array gets initialized

Listing 13.8 LST13_8.TXT: Initializing the Array Elements to Different Values.

for (int x=0; x<3; ++x)

{

for (int y=0; y<3; ++y)

{

Trang 12

table[x][y] = x + y * 4;

}

}

Example: Creating a Two-Dimensional Array

Suppose that you need a table-like array that can hold 80 integers in eight columns and 10 rows First,you'd declare the array like this:

int numbers[][];

After declaring the array, you need to create it in memory, like this:

numbers = new int[8][10];

The last step is to initialize the array, probably using nested for loops:

for (int x=0; x<8; ++x)

for (int y=0; y<10; ++y)

numbers[x][y] = 0;

These lines initialize the numbers[][] array to all zeroes

Example: Using Two-Dimensional Arrays in an

Applet

To be sure you understand how arrays work, you'll put a two-dimensional array to work in a programcalled Applet18 The Applet18 applet creates and initializes a two-dimensional array with six columnsand eight rows (Try to imagine the elements of this array as the rows and columns of a spreadsheet.) Theprogram then prints the contents of the array in the Applet's display area, so you can see that the arraytruly holds the values to which it was initialized Listing 13.9 is the program, whereas Figure 13.5 showsthe applet running under the Appletviewer application

Trang 13

Figure 13.5 : This is Applet18 running under Appletviewer.

Listing 13.9 Applet18.java: Using a Two-Dimensional Array.

Trang 14

Tell Java that the program uses classes in the awt package.

Tell Java that the program uses classes in the applet package

Derive the Applet18 class from Java's Applet class

Declare a two-dimensional integer array

Override the Applet class's init() method

Create an array with six columns and eight rows

Loop from 0 to 5

Loop from 0 to 7

Initialize the currently indexed array element

Override the Applet class's paint() method

Loop from 0 to 5

Loop from 0 to 7

Convert the array element to a string

Display the array element's value

Notice in init() and paint() how the nested loops don't have curly braces like the example shown

in Listing 13.8 This is because when you have only one statement in a program block, the curly bracesare optional In Applet18's init() method, the outside loop contains only one statement, which is theinner for loop The inner for loop also contains only a single statement, which is the line that

initializes the currently indexed element of the array In the paint() method, the outer loop containsonly one statement, which is the inner for loop However, the inner loop contains two statements, so thecurly braces are required in order to mark off that program block

Trang 15

of the table and the second identifies the row.

CHAP13 folder of this book's CD-ROM.)

Figure 13.6 : This is the ScoreApplet applet running under Appletviewer.

7

Trang 16

Chapter 10

The while and do-while Loops

CONTENTS

The while Loop

Example: Using a while Loop

Example: Using a while Loop in a Program

The do-while Loop

Example: Using a do-while Loop

Every programming language must have some form of looping command to instruct a computer to

perform repetitive tasks Java features three types of looping: for loops, while loops, and do-whileloops In this chapter, you learn about the latter two types of loops In the next chapter, you'll cover forloops

NOTE

In computer programs, looping is the process of repeatedly running ablock of statements Starting at the top of the block, the statements areexecuted until the program reaches the end of the block, at whichpoint the program goes back to the top and starts over The statements

in the block may be repeated any number of times, from none toforever If a loop continues on forever, it is called an infinite loop

Trang 17

The while Loop

One type of loop you can use in your programs is the while loop, which continues running until itscontrol expression becomes false The control expression is a logical expression, much like the logicalexpressions you used with if statements In other words, any expression that evaluates to true or

false can be used as a control expression for a while loop Here's an example of simple while loop:

NOTE

Notice how, in the previous example of a while loop, the programfirst sets the value of the control variable (num) to 1 Initializing yourcontrol variable before entering the while loop is extremely

important If you don't initialize the variable, you don't know what itmight contain, and therefore the outcome of the loop is unpredictable

In the above example, if num happened to be greater than 10, the loopwouldn't happen at all Instead, the loop's control expression wouldimmediately evaluate to false, and the program would branch tothe statement after the curly braces Mistakes like this make

programmers growl at their loved ones

Example: Using a while Loop

Although the previous example has only a single program line in the body of the while loop, you canmake a while loop do as much as you want As usual, to add more program lines, you create a programblock using braces This program block tells Java where the body of the loop begins and ends For

example, suppose you want to create a loop that not only increments the loop control variable, but alsodisplays a message each time through the loop You might accomplish this task as shown in Listing 10.1

Listing 10.1 LST10_1.TXT: Using a while Loop.

num = 0;

Trang 18

Initialize the loop control variable.

Check whether num is less than 10

Increment the loop control variable

Create a string from the value of num

Display a message on the screen

Display the value of num

NOTE

The body of a loop comprises the program lines that are executed

when the loop control expression is true Usually, the body of a loop

is enclosed in braces, creating a program block

The pseudocode given after the listing illustrates how this while loop works The thing to notice is howall the statements that Java should execute if the loop control expression is true are enclosed by braces

As I mentioned previously, the braces create a program block, telling Java where the body of the loopbegins and ends

CAUTION

Always initialize (set the starting value of) any variable used in awhile loop's control expression Failure to do so may result in yourprogram skipping over the loop entirely (Initializing a variable meanssetting it to its starting value If you need a variable to start at a

specific value, you must initialize it yourself.) Also, be sure toincrement or decrement the control variable as appropriate in the

body of a loop Failure to do this could result in an infinite loop,

which is when the loop conditional never yields a true result, causingthe loop to execute endlessly

Trang 19

Example: Using a while Loop in a Program

As with most things in life, you learn best by doing So, in this example, you put together an applet thatuses a while loop to create its display Listing 10.2 is the applet's source code, whereas Listing 10.3 isthe HTML document that loads and runs the applet Figure 10.1 shows the Applet8 applet running inAppletviewer If you need a reminder on how to compile and run an applet, follow these steps:

Figure 10.1 : Applet8 running in Appletviewer.

Type the source code shown in Listing 10.2 and save it in your CLASSES folder, naming the fileApplet8.java (You can copy the source code from the CD-ROM, if you like, and thus save

textField1 = new TextField(5);

textField2 = new TextField(5);

Trang 20

int count = start;

while (count <= end)

Trang 21

Tell Java that the program uses classes in the awt package.

Tell Java that the program uses classes in the applet package

Derive the Applet8 class from Java's Applet class

Declare TextField objects called textField1 and textField2

Override the Applet class's init() method

Create the two TextField objects

Add the two TextField objects to the applet

Initialize the TextField objects to "1" and "10."

Override the Applet class's paint() method

Print a prompt for the user

Get the number from the first TextField object

Convert the number from text to an integer

Get the number from the second TextField object

Convert the number from text to an integer

Initialize the row counter

Initialize the loop control variable, count

Loop from the starting value to the ending value

Initialize a string to "Count = "

Add the loop counter to the text string

Draw the text string in the applet's display area

Increment the row counter

Override the Applet class's action() method

Tell Java to redraw the applet's display area

Tell Java that the action() method finished successfully

Listing 10.3 APPLET8.htmL: Applet8's HTML Document.

Trang 22

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

Figure 10.2 : Applet8 will count however you tell it to.

NOTE

If you enter a pair of numbers with a wide range, the applet's outputwill run off the bottom of the applet This won't hurt anything, butyou'll be unable to see the entire output In addition, if you make thestarting value greater than the ending value, no output will appear inthe applet's display area This is because the while loop's

conditional expression never evaluates to true

The do-while Loop

Java also features do-while loops A do-while loop is much like a while loop, except a

do-while loop evaluates its control expression at the end of the loop rather than at the beginning Sothe body of the loop-the statements between the beginning and end of the loop-is always executed at leastonce In a while loop, the body of the loop may or may not ever get executed Listing 10.4 shows how

a do-while loop works

Listing 10.4 LST10_4.TXT: Using a do-while Loop.

Trang 23

Example: Using a do-while Loop

Near the beginning of this chapter, you saw an example of a while loop whose body contained multiplestatements By using braces to mark off a program block, you can do the same thing with a do-whileloop Listing 10.5 shows how to create a multiple line do-while loop:

Listing 10.5 LST10_5.TXT: A Multiple-Line do-while loop.

Trang 24

while (num < 10);

Initialize the loop control variable

Begin the do-while loop

Increment the loop control variable

Create a string from the value of num

Display a message on the screen

Display the value of num

Determine whether to repeat the loop

Example: Using a do-while Loop in a Program

Now it's time to put your knowledge of do-while loops to the test If you haven't yet picked up on thepattern, you may be surprised to learn that the next applet is called Applet9 Applet9 looks and acts a lotlike Applet8 In fact, as far as the user is concerned, they are almost exactly the same program However,the clever among you may have already guessed that Applet9 uses a do-while loop in place of thewhile loop This means that regardless of the values the user enters into the applet's TextField

controls, the applet will always display at least one line of text Listing 10.6 is the applet Modify theHTML document from Listing 10.3, replacing all occurrences of Applet8 with Applet9, in order to runthe new version of the applet

Listing 10.6 Applet9.java: Source Code for Applet9.

Trang 25

{

textField1 = new TextField(5);

textField2 = new TextField(5);

Trang 26

Figure 10.3 : The do-while loop always executes at least once.

Summary

By using loops, you can easily program your applets to perform repetitive operations Although loopsmay seem a little strange to you at this point, you'll find more and more uses for them as you write yourown applets Just remember that a while loop may or may not ever execute depending on how the

Ngày đăng: 22/07/2014, 16:21

TỪ KHÓA LIÊN QUAN