intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

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

Chia sẻ: Thái Duy Ái Ngọc | Ngày: | Loại File: PDF | Số trang:52

91
lượt xem
27
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'giáo trình java by example phần 7', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: giáo trình Java By Example phần 7

  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); add(textField1); add(textField2); add(textField3); textField1.setText("0"); textField2.setText("0"); textField3.setText("0"); } public void paint(Graphics g) http://www.ngohaianh.info
  2. { g.drawString("Your bowlers' averages are: ", 50, 80); String s = textField1.getText(); g.drawString(s, 75, 110); avg1 = Integer.parseInt(s); s = textField2.getText(); g.drawString(s, 75, 125); avg2 = Integer.parseInt(s); s = textField3.getText(); g.drawString(s, 75, 140); avg3 = Integer.parseInt(s); } public boolean action(Event event, Object arg) { repaint(); return true; } } 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? http://www.ngohaianh.info
  3. 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: float numbers[]; Another way to declare the array is to move the square brackets to after the data type, like this: float[] numbers; After declaring the array, you need to create it in memory. Java lets you create arrays only using the new operator, like this: http://www.ngohaianh.info
  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
  5. public void init() { textField = new TextField[3]; avg = new int[3]; for (int x=0; x
  6. } } public boolean action(Event event, Object arg) { repaint(); return true; } } 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 like this: TextField textField[]; http://www.ngohaianh.info
  7. int avg[]; These declarations are much like other declarations you've seen, except both of the variable names end with 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 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: Listing 13.3 LST13_3.TXT: Initializing an Array without Looping. textField[0] = new TextField(5); add(textField[0]); textField[0].setText("0"); textField[1] = new TextField(5); add(textField[1]); textField[1].setText("0"); textField[2] = new TextField(5); add(textField[2]); textField[2].setText("0"); http://www.ngohaianh.info
  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 in Listing 13.4. Listing 13.4 LST13_4.TXT: Initializing an Array Using a Loop. for (int x=0; x
  9. { String s = textField[x].getText(); g.drawString(s, 75, 110 + x*15); avg[x] = Integer.parseInt(s); } 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. http://www.ngohaianh.info
  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. table[0][0] = 0; table[1][0] = 1; table[2][0] = 2; table[3][0] = 3; table[0][1] = 4; table[1][1] = 5; table[2][1] = 6; table[3][1] = 7; table[0][2] = 8; table[1][2] = 9; table[2][2] = 10; table[3][2] = 11; table[0][3] = 12; table[1][3] = 13; table[2][3] = 14; table[3][3] = 15; 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]; http://www.ngohaianh.info
  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. for (int x=0; x
  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
  13. Figure 13.5 : This is Applet18 running under Appletviewer. Listing 13.9 Applet18.java: Using a Two-Dimensional Array. import java.awt.*; import java.applet.*; public class Applet18 extends Applet { int table[][]; public void init() { table = new int[6][8]; for (int x=0; x
  14. { String s = String.valueOf(table[x][y]); g.drawString(s, 50+x*25, 50+y*15); } } } 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 initializes the currently indexed element of the array. In the paint() method, the outer loop contains only one statement, which is the inner for loop. However, the inner loop contains two statements, so the curly braces are required in order to mark off that program block. Summary Arrays are a powerful data structure that enable you to store many related values using the same variable name. A one-dimensional array is a lot like a list of values that you can access by telling Java the appropriate subscript (or index). But because array subscripts always start at 0, the subscript is always one less than the number of the associated element. You can also create multidimensional arrays (or, to be more precise, arrays of arrays). A two-dimensional array is organized much like a table. To access the elements of a two-dimensional array, you need two subscripts. The first subscript identifies the column http://www.ngohaianh.info
  15. of the table and the second identifies the row. Review Questions 1. What is an array? 2. Why are arrays easier to use than a bunch of related variables? 3. What is an array subscript? How is a subscript like an index? 4. What is a two-dimensional array? 5. If you had an array of 50 integers, what is the largest valid subscript? 6. What happens if you try to access a nonexistent array element? 7. Describe why a for loop is appropriate for accessing an array? 8. How would you use for loops to initialize a two-dimensional array? Review Exercises 1. Declare an array that can hold 50 integers. 2. Write the code that creates the array you declared in exercise 1. 3. Write a for loop that initializes the array to the values 50 through 99. 4. Write the Java code to declare and create a two-dimensional array with 10 columns and 15 rows. 5. Write nested for loops that initialize the array from exercise 4 to the values 0 through 149. 6. Write the Java code needed to display, in table form, the values in the array from exercise 5. 7. Modify Applet17 so that it stores and displays not only the bowlers' scores, but also the bowlers' names. Create three TextField objects to enable the user to enter names and three for entering the scores. Name the program ScoreApplet.java. Figure 13.6 shows what the final applet should look like at startup. (You can find the solution to this programming problem in the CHAP13 folder of this book's CD-ROM.) Figure 13.6 : This is the ScoreApplet applet running under Appletviewer. http://www.ngohaianh.info
  16. Chapter 10 The while and do-while Loops CONTENTS The while Loop q Example: Using a while Loop r Example: Using a while Loop in a Program r The do-while Loop q Example: Using a do-while Loop r Example: Using a do-while Loop in a Program r Summary q Review Questions q Review Exercises q A computer handles repetitive operations especially well-it never gets bored, and it can perform a task as well the 10,000th time as it did the first. Consider, for example, a disk file containing 10,000 names and addresses. If you tried to type labels for all those people, you'd be seeing spots before your eyes in no time. On the other hand, a printer (with the aid of a computer) can tirelessly spit out all 10,000 labels-and with nary a complaint to the union. 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-while loops. In this chapter, you learn about the latter two types of loops. In the next chapter, you'll cover for loops. NOTE In computer programs, looping is the process of repeatedly running a block of statements. Starting at the top of the block, the statements are executed until the program reaches the end of the block, at which point the program goes back to the top and starts over. The statements in the block may be repeated any number of times, from none to forever. If a loop continues on forever, it is called an infinite loop. http://www.ngohaianh.info
  17. The while Loop One type of loop you can use in your programs is the while loop, which continues running until its control expression becomes false. The control expression is a logical expression, much like the logical expressions 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: num = 1; while (num < 10) ++num; Here the loop's control variable num is first set to 1. Then, at the start of the while loop, the program compares the value in num with 10. If num is less than 10, the expression evaluates to true, and the program executes the body of the loop, which in this case is a single statement that increments num. The program then goes back and checks the value of num again. As long as num is less than 10, the loop continues. But once num equals 10, the control expression evaluates to false and the loop ends. NOTE Notice how, in the previous example of a while loop, the program first sets the value of the control variable (num) to 1. Initializing your control variable before entering the while loop is extremely important. If you don't initialize the variable, you don't know what it might contain, and therefore the outcome of the loop is unpredictable. In the above example, if num happened to be greater than 10, the loop wouldn't happen at all. Instead, the loop's control expression would immediately evaluate to false, and the program would branch to the 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 can make a while loop do as much as you want. As usual, to add more program lines, you create a program block 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 also displays 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; http://www.ngohaianh.info
  18. while (num < 10) { ++num; String s = String.valueOf(num); g.drawString("num is now equal to:", 20, 40); g.drawString(s, 20, 55); } 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 how all 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 loop begins and ends. CAUTION Always initialize (set the starting value of) any variable used in a while loop's control expression. Failure to do so may result in your program skipping over the loop entirely. (Initializing a variable means setting it to its starting value. If you need a variable to start at a specific value, you must initialize it yourself.) Also, be sure to increment 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, causing the loop to execute endlessly. http://www.ngohaianh.info
  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 that uses a while loop to create its display. Listing 10.2 is the applet's source code, whereas Listing 10.3 is the HTML document that loads and runs the applet. Figure 10.1 shows the Applet8 applet running in Appletviewer. If you need a reminder on how to compile and run an applet, follow these steps: Figure 10.1 : Applet8 running in Appletviewer. 1. Type the source code shown in Listing 10.2 and save it in your CLASSES folder, naming the file Applet8.java. (You can copy the source code from the CD-ROM, if you like, and thus save on typing.) 2. Compile the source code by typing javac Applet8.java at the MS-DOS prompt, which gives you the Applet8.class file. 3. Type the HTML document shown in Listing 10.3, and save it to your CLASSES folder under the name APPLET8.htmL. 4. Run the applet by typing, at the MS-DOS prompt, appletviewer applet8.html. Listing 10.2 Applet8.java: An Applet That Uses a while Loop. import java.awt.*; import java.applet.*; public class Applet8 extends Applet { TextField textField1; TextField textField2; public void init() { textField1 = new TextField(5); textField2 = new TextField(5); http://www.ngohaianh.info
  20. add(textField1); add(textField2); textField1.setText("1"); textField2.setText("10"); } public void paint(Graphics g) { g.drawString("Enter start and end values above.", 50, 45); String s = textField1.getText(); int start = Integer.parseInt(s); s = textField2.getText(); int end = Integer.parseInt(s); int row = 0; int count = start; while (count
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2