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

Java By Example PHẦN 4 pdf

59 326 0

Đ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

Tiêu đề Java by Example Part 4
Trường học University of the Philippines
Chuyên ngành Computer Science
Thể loại Textbook
Thành phố Manila
Định dạng
Số trang 59
Dung lượng 1,9 MB

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

Nội dung

The second function in Listing 12.2 is the DrawInstructions subroutine, which is really just a Java function that returns no value to the calling function paint, in this case.. If you lo

Trang 1

Figure 12.1 : This is the Applet13 applet running under Appletviewer

Listing 12.1 Applet13.java: Printing Instructions in an Applet.

g.drawString("Try to guess the number I am", 48, 65);

g.drawString("thinking of The number will be", 48, 80); g.drawString("between 0 and 100 You have an", 48, 95); g.drawString("unlimited number of tries.", 48, 110);

g.drawString("Good Luck.", 95, 140);

}

}

Applet13 is about the simplest applet you can write All it does is display text The text comprises

instructions for playing a simple number game If you had to sum up in a couple of words the task

performed by Applet13's paint() method, you might come up with something like "Draw

Instructions," which is an excellent name for a function to handle that task Listing 12.2 is a new version

of the applet that isolates the instruction-display task in its own function When you run this applet, it looks identical to Applet13

Trang 2

Listing 12.2 Applet14.java: Placing the Instructions in a Function.

}

}

Now for the million-dollar question: How does this Applet14 work? The program is divided into two

Trang 3

functions The first is the paint() method, which Java calls whenever the applet's display area must be redrawn In this applet, paint() is at the highest level of your top-down design That is, no other part

of the program calls paint(), but paint() calls functions that are lower in level

The second function in Listing 12.2 is the DrawInstructions() subroutine, which is really just a Java function that returns no value to the calling function (paint(), in this case)

DrawInstructions() is one level down from the main program in the top-down design In

paint(), instead of having all the code that's needed to display the instructions, you only have a line that calls the function that handles this task This makes it easier to see what's going on in paint() If you need to see more detail, you can always drop down a level in your program and take a look at

DrawInstructions()

Defining and Calling Functions

There are two things you must do to use a function in a program The first thing you must do is define the function, which means that you must write all the program instructions that make up the function, placing the instructions between curly braces You must also determine what arguments the function must have

in order to perform its task In Applet14, the DrawInstructions() function definition looks like Listing 12.3

Listing 12.3 LST12_3.TXT: The DrawInstructions( ) Subroutine.

void DrawInstructions(Graphics g)

{

g.drawString("Try to guess the number I am", 48, 65);

Trang 4

g.drawString("thinking of The number will be", 48, 80);

g.drawString("between 0 and 100 You have an", 48, 95);

g.drawString("unlimited number of tries.", 48, 110);

g.drawString("Good Luck.", 95, 140);

}

The first line of Listing 12.3 tells Java the type of value returned from the function, the name of the

function, and the arguments that must be sent to the function when it's called In this case, the type of return value is void, which means the function returns no value The name of the function is

DrawInstructions, and its argument is a Graphics object called g (Notice that, in the function's first line, you must list both the argument type and argument name.) If you look at the paint()

method, you can see that Applet14 calls the DrawInstructions() function like this:

DrawInstructions(g);

This line tells Java that you want to execute the program code in the DrawInstructions() function and that you want to pass the Graphics object g to the function DrawInstructions() needs access to g because it is the Graphics object that has the drawString() method Without access to the Graphics object, DrawInstructions() cannot perform its task in the same way that the

drawString() method cannot display a string unless you give it the string and the location at which

to display the string

The second thing you must do to use a function is to call the function When you call a function, program execution jumps to the commands that make up the function All commands in the function are executed, after which the program returns to the line after the function call

NOTE

Trang 5

The arguments you place between the parentheses of a function call must be of the same type and in the same order as the arguments given in the function's first line That is, the call

DrawInstructions(g) and the first line of the function, DrawInstructions(Graphics g), match perfectly because the function call sends a Graphics object and the function

expects a Graphics object The names of the arguments, however, don't have to match For example, the function call DrawInstructions(g) and the function name

DrawInstructions(Graphics graph) are still a match

The only difference is that you'd have to refer to graph inside the DrawInstructions() function, rather than to g

Example: Using Functions to Return Values

In Java, functions are the main way you can break up your programs into modules But unlike when you used functions as subroutines, some types of functions return a value to the main program You've used this type of Java function before in this book The String class' valueOf() method is one The value

it returns is the numerical value of a string containing digits

You can assign a function's return value to a variable Suppose you have a function named GetNum()that calculates a number and returns it to your program A call to the function might look something like this:

int num = GetNum();

The function might look something like Listing 12.4

Listing 12.4 LST12_4.TXT: An Example of a Function

int GetNum()

{

++value;

Trang 6

return value;

}

Listing 12.4 shows some of the differences between using functions as subroutines (which return no value) and using functions to return values While functions being used as subroutines always start with the keyword void, functions that return values start with the keyword int, char, float or whatever type of return value you need Also, since subroutines return no value, they need no return statement But as you can see, the GetNum() function returns a value by using the return keyword along with the value to be returned If you fail to include the return command in the body of a function that returns a value, Java's compiler will give you an error message

NOTE

Normally, arguments passed into a function are passed by value,

which means that a copy of the passed value is given to the function When you change the value of the argument in the function, you are changing the copy, while the original value stays

the same However, some arguments are passed by reference, which

means that the original object is passed to the function In this case, changing the argument's value in the function changes the original value, too You learn about passing by reference in Chapter 13,

"Arrays."

Example: Putting Functions to Work

Think you understand functions now? The applet you'll build in this example will put your knowledge to the test Listing 12.5 is the applet's source code, whereas Listing 12.6 is the HTML document that'll load and run the applet Figure 12.2 shows what the applet looks like when it's running under Appletviewer

Figure 12.2 : This is the Applet15 applet running under Appletviewer

Listing 12.5 APPLET15.JAVA: Using Functions in a Java Applet.

Trang 7

/////////////////////////////////////// TextField textField1;

int guesses;

int number;

//////////////////////////////////////// // Overridden methods

//////////////////////////////////////// public void init()

Trang 8

public void paint(Graphics g)

Trang 9

g.drawString("Good Luck.", 95, 140); }

int GetGuess()

{

String s = textField1.getText(); int num = Integer.parseInt(s);

Trang 10

g.drawString("Your guess is too low.", 70, 185); else if (guess > number)

g.drawString("Your guess is too high.", 70, 185); else

g.drawString("You guessed the number!", 65, 185); }

}

Tell Java that the program uses classes in the awt package

Tell Java that the program uses classes in the applet package

Tell Java that the program uses the lang package's Math class

Derive the Applet15 class from Java's Applet class

Declare the class's data fields

Override the Applet class's init() method

Create the TextField object

Add the TextField object to the applet

Initialize the text in the TextField object to "50."

Initialize the guess counter to zero

Create the number that the player must guess

Override the Applet class's paint() method

Print the game's instructions

Get the player's guess

Show the appropriate message based on the guess

Override the Applet class's action() method

Increment the guess counter

Tell Java to redraw the applet's display area

Tell Java that the action() method finished successfully

Define the private DrawInstructions() method

Display the game instructions in the applet

Define the private GetGuess() method

Get the text from the TextField object

Convert the text to an integer

Return the integer to the calling function

Define the private CreateNumber() method

Trang 11

Calculate a random number from 0 to 1.

Convert the random number to an integer between 1 and 100

Return the random number to the calling function

Define the private ShowMessage() method

Display the number of guesses so far

Display the results of the player's latest guess

Listing 12.6 APPLET15.htmL: Applet15's HTML Document

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

Yes, it's true that Applet15 is much larger than the example applets you've used so far in this book, but the program needs to be long in order to accommodate several different functions By analyzing the program's flow, you can determine whether or not you understand how functions work

Start with the paint() method By examining the function calls it contains, you can get a good idea of what the program does Specifically, the program displays the game's instructions, gets a guess from the user, and then displays a message to the user If you were only interested in examining the paint()

Trang 12

method, you wouldn't have to go any further; the details of how these other functions work are tucked out

of your way

If you wanted to see exactly how the program prints the game's instructions, however, you could find the DrawInstructions() method in the source code The same is true for the other functions called in the paint() method

You can see that some of the functions return values and others don't Similarly, some functions require arguments and others don't How the function is constructed depends on whether it must calculate and return a value to the program (such as in CreateNumber()) and whether the function requires values from the program in order to perform its task (such as ShowMessage(), which needs the Graphicsobject and the player's latest guess)

There are probably several lines of Java source code in Listing 12.5 that don't make sense to you right now The pseudocode section following the listing describes, in general, what the program is doing You'll learn about many of the details in other chapters At this point, you only need to worry about being able to follow the function calls

Review Questions

1 What is top-down programming?

2 How do functions make top-down programming possible?

3 Do all functions return values?

4 What are arguments and how are they used?

5 What is meant by "defining a function"?

6 How do you return a value from a function?

7 How do the arguments given in a function call relate to the arguments accepted by the function?

8 How do you determine how to break a program up into functions?

Trang 13

Review Exercises

1 Write a function that prints a two-line message to the user

2 Write a function that returns the number 1 as an integer

3 Write a function that accepts two integer arguments and returns the sum of the arguments

4 Modify the function from exercise 3 so that it sums the two arguments, calls yet another function that multiplies the two arguments, sums the product and the original sum, and returns the result Write the function that performs the multiplication

5 Modify Applet15 by adding a function that starts the game over each time the user guesses the number That is, after the user guesses the number, the program should select a new random number and continue the game Name the program GuessApplet.java (You can find the solution to this programming problem in the CHAP12 folder of this book's CD-ROM.)

Trang 14

Chapter 13

Arrays

CONTENTS

● An Introduction to Arrays

❍ Example: Creating an Array

❍ Example: Using a Variable as a Subscript

● Multidimensional Arrays

❍ Example: Creating a Two-Dimensional Array

● Example: Using Two-Dimensional Arrays in an Applet

Until now, you've learned about various types of numerical variables, including integers, long integers, floating-point, and double floating-point variables You also know about string variables, which can hold text Now that you have a good understanding of these data types, it's time to explore one last data type-a handy data structure called an array

An Introduction to Arrays

Often in your programs, you'll want to store many values that are related in some way Suppose you manage a bowling league, and you want to keep track of each player's average One way to do this is to give each player a variable in your program, as shown in Listing 13.1 Figure 13.1 shows the applet running under Appletviewer

Trang 15

Figure 13.1 : This is Applet16 running under Appletviewer

Listing 13.1 Applet16.java: Using Variables to Track Scores.

textField1 = new TextField(5);

textField2 = new TextField(5);

textField3 = new TextField(5);

Trang 17

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 three variables avg1, avg2, and avg3

Nothing too tricky going on here, right?

Now examine the listing Remember in Chapter 10, "The while and do-while Loops," when you learned 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 this code, 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 An array is a variable that can hold more than one value When you first studied variables, you learned that a variable is like a box in memory that holds a single value Now, if you take a bunch of these boxes and put them together, what do you have? You have an array For example, to store the bowling averages for your three bowlers, you'd need an array that can hold three values You could call this array avg You can even create an array for a set of objects like the TextField objects Applet16 uses to get bowling scores 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 is stored For example, to refer to the first average in your avg array, you'd write avg[0] The subscript is the 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 array like this:

Trang 18

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 how the 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 the number 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 subscript variable 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 less code than in the original program Listing 13.2 shows how this is done

Trang 19

Listing 13.2 Applet17.java: Using Arrays.

textField = new TextField[3];

avg = new int[3];

Trang 20

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

Trang 21

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 like this:

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 follow new with the data type and the size of the array in square brackets In other words, the first line above creates an array that can hold three TextField objects The second line creates an array that can hold three integers

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

something like Listing 13.3:

Trang 22

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

textField[0] = new TextField(5);

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

Trang 23

The first time through the loop, x is equal to 0, so that element 0 (the first element) of the textFieldarray is being manipulated The next time through the loop, x is 1, so that element 1 of the array is being manipulated in the body of the loop Finally, when x is 2, the program takes care of the third array

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

CAUTION

Be careful not to try accessing a nonexistent array element For example, in Listing 13.4, if you tried to access textField[3], you'd be beyond the boundaries of the array Java will generate an exception when this happens, which means your applet may or may not 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's arrays 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.

Trang 24

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 of elements 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 the second element, and so on The reason numbers[0] is the first element of the array is because of the number 0 inside the subscript.It is the number inside the subscript that defines which array location is being 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 arrays you've used so far in this chapter The next type of array in the figure is two-dimensional, which works like 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 to create 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, you might use the lines shown in Listing 13.6, which would give you the array shown in Figure 13.4

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

Trang 25

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[][] array shown in Figure 13.4, you use a line like this:

int value = table[3][2];

Trang 26

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] gets set to 5 Then the inside loop sets y to 1, which means table[0][1] gets set to 5 When the inner loop finishes, the program branches back to the outer loop, setting x to 1 The inner loop repeats again, only this time with x equal to 1 and y going from 0 to 2 Finally, when both loops finish, the entire array is initialized

Of course, to create the array shown in Figure 13.4 with loops, you have to be a little more tricky, as shown 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)

Trang 27

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

Trang 28

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

Figure 13.5 : This is Applet18 running under Appletviewer

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

Trang 29

public void paint(Graphics g)

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 braces are optional In Applet18's init() method, the outside loop contains only one statement, which is the inner for loop The inner for loop also contains only a single statement, which is the line that

Ngày đăng: 12/08/2014, 19:21

TỪ KHÓA LIÊN QUAN