Creating Your First Object

Một phần của tài liệu sams teach yourselfa java in 24 hours 6th edition (Trang 104 - 116)

ptg7068951

for (int dex = 0; dex < 1000; dex++) { if (dex % 12 == 0) {

System.out.println(“#: “ + dex);

} }

This loop displays every number from 0 to 999 evenly divisible by 12.

Every forloop has a variable that determines when the loop should begin and end. This variable is called the counter (or index). The counter in the preceding loop is the variable dex.

The example illustrates the three parts of a forstatement:

. The initialization section: In the first part, the dexvariable is given an initial value of 0.

. The conditional section: In the second part, there is a conditional test like one you might use in an ifstatement: dex < 1000.

. The change section: The third part is a statement that changes the value of the dexvariable, in this example by using the increment operator.

In the initialization section, you set up the counter variable. You can create the variable in the forstatement, as the preceding example does with the integer variable dex. You also can create the variable elsewhere in the pro- gram. In either case, you should give the variable a starting value in this sec- tion of the forstatement. The variable has this value when the loop starts.

The conditional section contains a test that must remain truefor the loop to continue looping. When the test is false, the loop ends. In this example, the loop ends when the dexvariable is equal to or greater than 1,000.

The last section of the forstatement contains a statement that changes the value of the counter variable. This statement is handled each time the loop goes around. The counter variable has to change in some way or the loop never ends. In the example, dexis incremented by one in the change sec- tion. If dexwas not changed, it would stay at its original value of 0 and the conditional dex < 1000always would be true.

The forstatement’s block is executed during each trip through the loop.

The preceding example had the following statements in the block:

if (dex % 12 == 0) {

System.out.println(“#: “ + dex);

}

ptg7068951

forLoops 97

These statements are executed 1,000 times. The loop starts by setting the dexvariable equal to 0. It then adds 1 to dexduring each pass through the loop and stops looping when dexis no longer less than 1,000.

As you have seen with ifstatements, a forloop does not require brackets if it contains only a single statement. This is shown in the following example:

for (int p = 0; p < 500; p++)

System.out.println(“I will not sell miracle cures”);

This loop displays the text “I will not sell miracle cures” 500 times.

Although brackets are not required around a single statement inside a loop, you can use them to make the block easier to spot.

The first program you create during this hour displays the first 200 multi- ples of 9: 9 ×1, 9 ×2, 9 ×3, and so on, up to 9 ×200. In NetBeans, create a new empty Java file named Ninesand enter the text in Listing 8.1. When you save the file, it is stored as Nines.java.

LISTING 8.1 The Full Text of Nines.java

1: class Nines {

2: public static void main(String[] arguments) { 3: for (int dex = 1; dex <= 200; dex++) { 4: int multiple = 9 * dex;

5: System.out.print(multiple + “ “);

6: } 7: } 8: }

The Ninesprogram contains a forstatement in Line 3. This statement has three parts:

. Initialization: int dex = 1, which creates an integer variable called dexand gives it an initial value of 1.

. Conditional: dex <= 200, which must be true during each trip through the loop. When it is not true, the loop ends.

. Change: dex++, which increments the dexvariable by one during each trip through the loop.

Run the program by choosing Run, Run File in NetBeans. The program produces the following output:

NOTE

An unusual term you might hear in connection with loops is iter- ation. An iteration is a single trip through a loop. The counter variable that is used to control the loop is called an iterator.

ptg7068951 Output▼

9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 144 153 162 171 180 189 198 207 216 225 234 243 252 261 270 279 288 297 306 315 324 333 342 351 360 369 378 387 396 405 414 423 432 441 450 459 468 477 486 495 504 513 522 531 540 549 558 567 576 585 594 603 612 621 630 639 648 657 666 675 684 693 702 711 720 729 738 747 756 765 774 783 792 801 810 819 828 837 846 855 864 873 882 891 900 909 918 927 936 945 954 963 972 981 990 999 1008 1017 1026 1035 1044 1053 1062 1071 1080 1089 1098 1107 1116 1125 1134 1143 1152 1161 1170 1179 1188 1197 1206 1215 1224 1233 1242 1251 1260 1269 1278 1287 1296 1305 1314 1323 1332 1341 1350 1359 1368 1377 1386 1395 1404 1413 1422 1431 1440 1449 1458 1467 1476 1485 1494 1503 1512 1521 1530 1539 1548 1557 1566 1575 1584 1593 1602 1611 1620 1629 1638 1647 1656 1665 1674 1683 1692 1701 1710 1719 1728 1737 1746 1755 1764 1773 1782 1791 1800

The output window in NetBeans does not wrap text, so all the numbers appear on a single line. To make the text wrap, right-click the output pane and choose Wrap text from the pop-up menu.

while Loops

The whileloop does not have as many different sections as a forloop. The only thing it needs is a conditional test, which accompanies the while statement. The following is an example of a whileloop:

while (gameLives > 0) {

// the statements inside the loop go here }

This loop continues repeating until the gameLivesvariable is no longer greater than 0.

The whilestatement tests the condition at the beginning of the loop before any statements in the loop have been handled. If the tested condition is falsewhen a program reaches the whilestatement for the first time, the statements inside the loop are ignored.

If the whilecondition is true, the loop goes around once and tests the whilecondition again. If the tested condition never changes inside the loop, the loop keeps looping indefinitely.

The following statements cause a whileloop to display the same line of text several times:

ptg7068951

do-whileLoops 99

int limit = 5;

int count = 1;

while (count < limit) {

System.out.println(“Pork is not a verb”);

count++;

}

Awhileloop uses one or more variables set up before the loop statement.

In this example, two integer variables are created: limit, which has a value of 5, and count, which has a value of 1.

The whileloop displays the text “Pork is not a verb” four times. If you gave the countvariable an initial value of 6 instead of 1, the text never would be displayed.

do - while Loops

The do-whileloop is similar to the whileloop, but the conditional test goes in a different place. The following is an example of a do-whileloop:

do {

// the statements inside the loop go here } while (gameLives > 0);

Like the whileloop, this loop continues looping until the gameLivesvari- able is no longer greater than 0. The do-whileloop is different because the conditional test is conducted after the statements inside the loop, instead of before them.

When the doloop is reached for the first time as a program runs, the state- ments between the doand whileare handled automatically, and then the whilecondition is tested to determine whether the loop should be repeat- ed. If the whilecondition is true, the loop goes around one more time. If the condition is false, the loop ends. Something must happen inside the doand whilestatements that changes the condition tested with while, or the loop continued indefinitely. The statements inside a do-whileloop always are handled at least once.

The following statements cause a do-whileloop to display the same line of text several times:

int limit = 5;

int count = 1;

do {

System.out.println(“I will not Xerox my butt”);

count++;

} while (count < limit);

ptg7068951 Like a whileloop, a do-whileloop uses one or more variables that are set

up before the loop statement.

The loop displays the text “I will not Xerox my butt” four times. If you gave the count variable an initial value of 6 instead of 1, the text would be displayed once, even though countis never less than limit.

In a do-whileloop, the statements inside the loop are executed at least once even if the loop condition is falsethe first time around.

Exiting a Loop

The normal way to exit a loop is for the tested condition to become false. This is true of all three types of loops in Java. There might be times when you want a loop to end immediately, even if the condition being tested is still true. You can accomplish this with abreakstatement, as shown in the following code:

int index = 0;

while (index <= 1000) { index = index + 5;

if (index == 400) { break;

} }

Abreakstatement ends the loop that contains the statement.

In this example, the whileloop loops until the indexvariable is greater than 1,000. However, a special case causes the loop to end earlier than that:

If indexequals 400, the breakstatement is executed, ending the loop immediately.

Another special-circumstance statement you can use inside a loop is con- tinue. The continuestatement causes the loop to exit its current trip through the loop and start over at the first statement of the loop. Consider the following loop:

int index = 0;

while (index <= 1000) { index = index + 5;

if (index == 400) continue;

System.out.println(“The index is “ + index);

}

ptg7068951

Naming a Loop 101

In this loop, the statements are handled normally unless the value of index equals 400. In that case, the continuestatement causes the loop to go back to the whilestatement instead of proceeding normally to the System.out.println()statement. Because of the continuestatement, the loop never displays the following text:

The index is 400

You can use the breakand continuestatements with all three kinds of loops.

The break statement makes it possible to create a loop in your program that’s designed to run forever, as in this example:

while (true) {

if (quitKeyPressed == true) { break;

} }

Naming a Loop

Like other statements in Java programs, you can place loops inside each other. The following shows a forloop inside a whileloop:

int points = 0;

int target = 100;

while (target <= 100) {

for (int i = 0; i < target; i++) { if (points > 50)

break;

points = points + i;

} }

In this example, the breakstatement causes the forloop to end if the pointsvariable is greater than 50. However, the whileloop never ends because targetis never greater than 100.

In some cases, you might want to breakout of both loops. To make this possible, you have to give the outer loop—in this example, the whilestate- ment—a name. To name a loop, put the name on the line before the begin- ning of the loop and follow it with a colon (:).

When the loop has a name, use the name after the breakor continuestate- ment to indicate the loop to which the breakor continuestatement applies. The following example repeats the previous one with the excep- tion of one thing: If the pointsvariable is greater than 50, both loops end.

ptg7068951

int points = 0;

int target = 100;

targetLoop:

while (target <= 100) {

for (int i = 0; i < target; i++) { if (points > 50)

break targetLoop;

points = points + i;

} }

When a loop’s name is used in a breakor continuestatement, the name does not include a colon.

Complex for Loops

Aforloop can be more complex, including more than one variable in its initialization, conditional, and change sections. Each section of a forloop is set off from the other sections with a semicolon (;). Aforloop can have more than one variable set up during the initialization section and more than one statement in the change section, as in the following code:

int i, j;

for (i = 0, j = 0; i * j < 1000; i++, j += 2) {

System.out.println(i + “ * “ + j + “ = “+ (i * j));

}

In each section of the forloop, commas are used to separate the variables as in i = 0, j = 0. The example loop displays a list of equations where the iand jvariables are multiplied together. The ivariable increases by one, and the jvariable increases by two during each trip through the loop.

When imultiplied by jis equal or greater than 1,000, the loop ends.

Sections of a forloop also can be empty. An example of this is when a loop’s counter variable already has been created with an initial value in another part of the program, as in the following:

for ( ; displayCount < endValue; displayCount++) { // loop statements would be here

}

Testing Your Computer Speed

This hour’s workshop is a Java program that performs a benchmark, a test that measures how fast computer hardware or software is operating. The

ptg7068951

Testing Your Computer Speed 103

Benchmarkprogram uses a loop statement to repeatedly perform the fol- lowing mathematical expression:

double x = Math.sqrt(index);

This statement calls the Math.sqrt()method to find the square root of a number. You learn how methods work during Hour 11, “Describing What Your Object Is Like.”

The benchmark you’re creating sees how many times a Java program can calculate a square root in one minute.

Use NetBeans to create a new empty Java file called Benchmark. Enter the text of Listing 8.2 and save the program when you’re done.

LISTING 8.2 The Full Source Code of Benchmark.java 1: class Benchmark {

2: public static void main(String[] arguments) { 3: long startTime = System.currentTimeMillis();

4: long endTime = startTime + 60000;

5: long index = 0;

6: while (true) {

7: double x = Math.sqrt(index);

8: long now = System.currentTimeMillis();

9: if (now > endTime) { 10: break;

11: } 12: index++;

13: }

14: System.out.println(index + “ loops in one minute.”);

15: } 16: }

The following things take place in the program:

. Lines 1–2: The Benchmarkclass is declared and the main()block of the program begins.

. Line 3: The startTimevariable is created with the current time in milliseconds as its value, measured by calling the

currentTimeMillis()method of Java’s Systemclass.

. Line 4: The endTimevariable is created with a value 60,000 higher than startTime. Because one minute equals 60,000 milliseconds, this sets the variable one minute past startTime.

. Line 5: Alongnamed indexis set up with an initial value of 0.

ptg7068951 . Line 6: The whilestatement begins a loop using trueas the condi-

tional, which causes the loop to continue forever (in other words, until something else stops it).

. Line 7: The square root of indexis calculated and stored in the x variable.

. Line 8: Using currentTimeMillis(), the nowvariable is created with the current time.

. Lines 9–11: If nowis greater than endTime, this signifies that the loop has been running for one minute and breakends the whileloop.

Otherwise, it keeps looping.

. Line 12: The indexvariable is incremented by 1 with each trip through the loop.

. Lines 14: Outside the loop, the program displays the number of times it performed the square root calculation.

The output of the application is shown in the Output pane in Figure 8.1.

FIGURE 8.1

The output of the Benchmark program.

The Benchmarkprogram is an excellent way to see whether your computer is faster than mine. During the testing of this program, my computer performed around 4.5 billion calculations. If your computer has better results, don’t just send me your condolences. Buy more of my books so I can upgrade.

Summary

Loops are a fundamental part of most programming languages. Animation created by displaying several graphics in sequence is one of many tasks you could not accomplish in Java or any other programming language without loops.

Every one of Bart Simpson’s chalkboard punishments has been document- ed on the Web. Visit www.snpp.com/guides/chalkboard.openings.html to see the list along with a Java program that runs on the page drawing Bart’s sayings on a green chalkboard.

ptg7068951 Q&A 105

Q&A

Q. The term initializationhas been used in several places. What does it mean?

A. It means to give something an initial value and set it up. When you cre- ate a variable and assign a starting value to it, you are initializing the variable.

Q. If a loop never ends, how does the program stop running?

A. Usually in a program where a loop does not end, something else in the program is set up to stop execution in some way. For example, a loop in a game program could continue indefinitely while the player still has lives left.

One bug that crops up often as you work on programs is an infinite loop, a loop that never stops because of a programming mistake. If one of the Java programs you run becomes stuck in an infinite loop, press the red alert icon to the left of the Output pane.

Q. How can I buy stock in the Green Bay Packers?

A. Unless the publicly owned NFL team decides to hold another stock sale, the only way to become a stockholder is to inherit shares in a will.

The Packers have sold stock in 1923, 1935, 1950, and 1997.

Approximately 112,000 people own 4.7 million shares in the team, despite the fact that they have very limited rights associated with the stock.

Holders don’t earn a dividend and can’t profit from their shares. They only can sell them back to the team and lose money in the deal. No indi- vidual can own more than 200,000 shares.

They do receive exclusive team merchandise offers and can attend an annu- al meeting to elect the seven-member board that manages the team.

In the 1923 stock sale that formed the franchise, 1,000 fans bought shares for $5 each. The 1997 sale raised $24 million for the Lambeau Field renovation.

More information on the stock can be found on the Web at www.packers.com/community/shareholders.html.

Workshop

The following questions test your knowledge of loops. In the spirit of the sub- ject matter, repeat each of these until you get them right.

ptg7068951

Quiz

1. What must be used to separate each section of a forstatement?

A. Commas B. Semicolons

C. Off-duty police officers

2. Which statement causes a program to go back to the statement that began a loop and then keep going from there?

A. continue

B. next

C. skip

3. Which loop statement in Java always runs at least once?

A. for

B. while

C. do-while

Answers

1. B.Commas are used to separate things within a section, but semi- colons separate sections.

2. A.Thebreakstatement ends a loop entirely, and continueskips to the next go-round of the loop.

3. C.Thedo-whileconditional isn’t evaluated until after the first pass through the loop.

Activities

If your head isn’t going in circles from all this looping, review the topics of this hour with the following activities:

. Modify the Benchmarkprogram to test the execution of simple mathe- matical calculation such as multiplication or division.

. Write a short program using loops that finds the first 400 numbers that are multiples of 13.

To see Java programs that implement these activities, visit the book’s website

ptg7068951 WHAT YOU’LL LEARN IN

THIS HOUR:

.Creating an array

.Setting the size of an array .Giving a value to an array

element

.Changing the information in an array

.Making multidimensional arrays

.Sorting an array No one benefited more from the development of the computer than Santa

Claus. For centuries, humankind has put an immense burden on him to gather and process information. Old St. Nick has to keep track of the fol- lowing things:

. Naughty children . Nice children . Gift requests

. Homes with impassable chimneys

. Women who want more from Santa than Mrs. Claus is willing to let him give

. Countries that shoot unidentified aircraft first and ask questions later Computers were a great boon to the North Pole. They are ideal for the stor- age, categorization, and study of information.

The most basic way that information is stored in a computer program is by putting it into a variable. The list of naughty children is an example of a collection of similar information. To keep track of a list of this kind, you can use arrays.

Arraysare groups of related variables that share the same type. Any type of information that can be stored as a variable can become the items stored in an array. Arrays can be used to keep track of more sophisticated types of information than a single variable, but they are almost as easy to create and manipulate as variables.

HOUR 9

Một phần của tài liệu sams teach yourselfa java in 24 hours 6th edition (Trang 104 - 116)

Tải bản đầy đủ (PDF)

(429 trang)