Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Repeating an Action with Loops

java



+ Font mai mare | - Font mai mic



Repeating an Action with Loops

One of the more annoying punishments for schoolchildren is to make them write something over and over again on paper or, for a capital offense, on the chalkboard. In one of his frequent trips to the board, cartoon problem child Bart Simpson had to write 'I will not trade pants with others' dozens of times. This kind of punishment might work on children, but it definitely would fail on a computer. They can repeat a task with ease.



As you might expect, every one of Bart Simpson's chalkboard punishments has been documented on the World Wide Web. Visit the following address to see the list:

<https://www.ncf.carleton.ca/~co378/HomePage.Chalk.html>

Computer programs are ideally suited to do the same thing over and over again because of loops. A loop is a statement or set of statements that will be repeated in a program. Some loops are set to occur a fixed number of times. Others can loop indefinitely. In the Java programs that you write, you will find many circumstances in which a loop is useful. You can use them to wait until a specific thing has taken place, such as a user clicking on a button. You can also use them to cause the computer to wait and do nothing for a brief period, such as in an animation program.

To create and control loops, you use a loop statement. A loop statement causes a computer program to return to the same place more than once. If the term seems unusual to you, think of what a stunt plane does when it loops: It completes a circle and returns to the place it started the loop. There are three loop statements in Java: for, do, and do-while. These loop statements are often interchangeable in a program because each can be made to work like the others. The choice of which loop statement to use in a program often depends on personal preference, but it's beneficial to learn how all three work. You frequently can simplify a loop section of a program by choosing the right statement.

The following topics will be covered during this hour:

Using the for loop

Using the do loop

Using the do-while loop

Exiting a loop prematurely

Naming a loop

for Loops

The most complex of the loop statements is for. The for loop is often used in cases where you want to repeat a section of a program for a fixed amount of times. It also can be used if the number of times the loop should be repeated is variable. The following is an example of a for loop:

for (int number = 0; number < 1000; number++)

This loop displays every number from 0 to 999 that is evenly divisible by 12. Every for loop has a variable that is used to determine when the loop should begin and end. This variable often is called the counter. The counter in the preceding loop is number.

The example illustrates the three parts of a for statement:

The initialization section: In the first part, the number variable is initialized with a value of 0.

The conditional section: In the second part, there is a conditional test like one you might use in an if statement. The test is number < 10000.

The change section: The third part is a statement that changes the value of the number variable by using the increment operator.

In the initialization section, you can set up the counter variable that you want to use in the for statement. You can create the variable inside the for statement, as the number variable was created in the example, or you can create the variable elsewhere in the program. In either case, the variable should be given a starting value in this section of the for statement. The variable will have this value when the loop starts.

The conditional section contains a test that must remain true for the loop to continue looping. Once the test is false, the loop will end. In this example, the loop will end when the number variable is no longer smaller than 1,000.

The last section of the for statement contains a Java statement that changes the value of the counter variable in some way. This statement is handled each time the loop goes around. The counter variable has to change in some way, or the loop will never end. For instance, in this example, number is incremented by one using the increment operator in the change section. If number were not changed, it would stay at its original value, 0, and the conditional number < 1000 would always be true.

The statements inside the bracket marks( ) are also executed during each trip through the loop. The bracketed area is usually where the main work of the loop takes place, although some loops do all of their work in the change section.

The preceding example had two statements within the marks:

if (number % 12 == 0)

System.out.println('#: ' + number);

These statements will be executed 1,000 times. The loop starts by setting the number variable equal to 0. It then adds 1 each pass through the loop and stops when number is no longer less than 1000. Every time number is evenly divisible by 12, the number is displayed next to the text .

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

Each section of a for loop is set off from the other sections with a semicolon ( ). A for loop 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:

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

These multiple statement sections of the for loop are set off by commas, as in i = 0, j = 0. This loop will display a list of equations where the i variable is multiplied by the j variable. The i variable increases by 1, and the j variable increases by 2 during each trip through the loop. Once i multiplied by j is no longer less than 1,000, the loop will end.

Sections of a for loop can be empty. An example of this would be if the counter variable has already been created with an initial value in another part of the program, as in the following:

for ( ; displayCount < endValue; displayCount++)

Caution: Because many Java statements end with a semicolon, an easy mistake to make is putting a semicolon at the end of a for statement, as in the following:

for (int i = 0; i < 100; i++);

In this example, the semicolon puts the statements in the brackets, value = value + i;, outside of the loop. As a result, nothing will happen as the for loop is handled. The program will compile without any errors, but you won't get the results you expect when it runs.

while Loops

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

while ( gameLives > 0)

This loop will continue repeating until the gameLives variable is no longer greater than 0. The while statement tests the condition at the beginning of the loop, before any statements of the loop have been handled.

When a program reaches the while statement for the first time, if the tested condition is false, the statements inside the loop will be ignored. If the while condition is true, the loop goes around once and tests the while condition again. If the tested condition never changes inside the loop, the loop will keep looping indefinitely.

do-while Loops

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

do while ( gameLives > 0 );

Like the previous while loop, this loop will continue looping until the gameLives variable is no longer greater than 0. The do-while loop is different because the conditional test is conducted after the statements inside the loop instead of before them.

When the do loop is reached for the first time as a program runs, the statements between the do and the while are handled automatically. Then the while condition is tested to determine whether the loop should be repeated. If the while condition is true, the loop goes around one more time. If the condition is false, the loop ends. Something must happen inside the do and while statements that changes the condition tested with while, or the loop will continue indefinitely. The statements inside a do-while loop will always be handled at least once.

If you're still confused about the difference between a while loop and a do-while loop, engage in a little role-playing and pretend you're a teenager who wants to borrow your father's car. If you are a teenager with a case of car envy, all the better. There are two strategies that you can take:

Borrow the car first and tell Dad later that you did it.

2.
Ask Dad before you borrow the car.

Strategy 1 has an advantage over Strategy 2 because you get to use the car once even if Dad doesn't want to let you use it. The do-while loop is like Strategy 1 because something happens once even if the loop condition is false the first time while is encountered. The while loop is like Strategy 2 because nothing will happen unless the while condition at the beginning is true. It all depends on the situation in your program. Sams.net makes no warranties express nor implied that your father will be happy if you borrow his car without telling him first.

Exiting a Loop

The normal way to exit a loop is for the condition that is tested to become false. This is true of all three types of loops in Java: for, while, and do-while. However, there might be times when you want a loop to end immediately even if the condition being tested is still true. You can do this with a break statement, as shown in the following code:

while (index <= 1000)

This loop will continue looping until the value of the index variable is greater than 1,000. However, a special case causes the loop to end even if the index variable is less than or equal to 1,000: If index equals 400, the loop ends immediately.

Another special-circumstance statement that you can use inside a loop is continue. The continue statement 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:

while (index <= 1000)

In this loop, the statements will be handled normally unless the value of index equals 400. In that case, the continue statement causes the loop to go back to the while statement instead of the System.out.println() statement. Because of the continue statement, the loop will never display the following text:

The index is 400

You can use the break and continue statements with all three kinds of Java loop statements.

Naming a Loop

Like other statements in Java programs, loops can be put inside of each other. The following shows a for loop inside of a while loop:

while ( totalCoconuts < 100)

The break statement will cause the for loop to end if the totalCoconuts variable equals 400 or greater. However, there might be a case where you want to break out of both loops for some reason. To make this possible, you have to give the outer loop--the while statement--a name. To name a loop, put the name on the line before the beginning of the loop and follow it with a colon ( ).

Once the loop has a name, you can use the name after the break or continue statement to indicate which loop the break or continue statement applies to. Note that although the name of the loop is followed by a colon at the spot where the loop begins, the colon is not used with the name in a break or continue statement. The following example repeats the previous one with the exception of one thing: If the totalCoconuts variable equals 400 or more, both loops are ended.

coconutLoop:

while ( totalCoconuts < 100)

Workshop: Teaching Your Computer a Lesson

This hour's workshop provides evidence that you cannot punish your computer in the same way that Bart Simpson is punished at the beginning of each episode of The Simpsons. Pretend you're a teacher, and the computer is the kid who contaminated your morning cup of coffee with Thorium 230. Even if you're the most strident liberal, you realize that the computer must be taught a lesson--it's not acceptable behavior to give the teacher radiation poisoning. Your computer must be punished, and the punishment is to display the same sentence over and over again.

The Repeat program will use a loop statement to handle a System.out.println() statement again and again. Once the computer has been dealt this punishment for 25,000 sentences or one minute, whichever comes first, it can stop running and think about the error of its ways.

A topic of heated debate here at Sams.net concerns whether the punishment is severe enough. Thorium is a silver-white metal that has a half-life of 80,000 years. Some scientists believe that it is as toxic as plutonium, and if it finds a home in someone's liver, bone marrow, or lymphatic tissue, Thorium 230 can cause cancer, leukemia, or lung cancer. A student who irradiates a teacher probably should receive three hours of in-school detention, at least.

Use your word processor to create a new file called Repeat.java. Enter the text of Listing 8.1 and save the file when you're done.

Listing 8.1. The full source code of Repeat.java.

1: import java.util.*;

2:

3: class Repeat

System.out.println('nI wrote the sentence ' + count + ' times.');

System.out.println('I have learned my lesson.');

}


The following things are taking place in this program:

Line 1: The import statement makes the java.util group of classes available to this program. You're going to use two of them, Calendar and GregorianCalendar, in order to keep track of time while the program is running.

Lines 2 and 3: The Repeat class is declared, and the main() block of the program begins.

Lines 5 and 6: The sentence variable is set up with the text of the punishment sentence, and the count variable is created with a value of 0.

Line 7: Using the GregorianCalendar class, which is used to retrieve the time information, the start variable is created with the current time.

Lines 8 and 9: The get() method of the GregorianCalendar class is used to retrieve the current minute and second and store them in the variables startMinute and startSecond.

Line 10: The GregorianCalendar roll() method is used to roll the value of the start variable one minute forward in time.

Lines 11 and 12: The get() method is used again to retrieve the minute and second for start and store them in the variables nextMinute and nextSecond.

Line 13: The while statement begins a loop using the count variable as the counter. When count hits 25,000, the loop will end.

Line 14: The punishment text, stored in the string variable sentence, is displayed.

Line 15: Using the GregorianCalendar class, the now variable is created with the current time.

Lines 16-18: Using one if statement inside of another, the program tests to see whether one minute has passed by comparing the current minute and second to the values of nextMinute and nextSecond. If it has passed, break ends the while loop.

Line 19: The marks the end of the while loop.

Lines 20 and 21: The computer displays the number of times it repeated the punishment sentence and claims to be rehabilitated.

Lines 22 and 23: The main() block of the program and the program are closed out with marks.

Compile the program with the javac compiler tool and then give it a try by typing the following at the command line:

java Repeat

Run this program several times to see how many sentences are displayed in a minute's time. The Repeat program is an excellent way to see whether your computer is faster than mine. During the testing of this workshop program, Repeat usually displayed from 8,700 to 9,100 sentences in a minute's time. If your computer displays the sentence more times than mine does, don't just send me your condolences. Buy more of my books so I can upgrade.

Caution: Although most of the programs that you will write in this book will work under version 1.0.2 of the Java Developer's Kit, the Repeat program will not compile successfully unless you use version 1.1 of the Kit. This program uses the GregorianCalendar class, which, like many other new features, was introduced with 1.1 and does not exist in 1.0.2. JavaSoft encourages the use of new features like this because they make improvements on the language. For example, GregorianCalendar is part of JavaSoft's effort to enable programmers to use different calendar systems in Java programs.

Summary

The information presented in this chapter is information that you will be coming back to again and again and again when you write programs. Loops are a fundamental part of most programming languages. In several of the hours to come, you'll get a chance to manipulate graphics so that you can produce animated effects. You couldn't do this without loops.

Q&A

Q Should the counter variable used in a for loop be created inside the for statement or before the loop begins?

A
The only time the counter should be created outside of the for loop, or any other loop for that matter, is when it needs to be used in another part of the program. A variable that is created in a loop or other kind of block statement only exists inside that block. You can't use the value in any other part of the program. This is good programming practice because it makes it harder to misuse variables--you can't set their value in one part of the program and use them somewhere else incorrectly. The concept of a variable existing in one part of a program and not existing anywhere else is called scope, and it's covered fully during Hour 11, 'Describing What Your Object Is Like.'

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

A
It means to give something an initial value and set it up. When you create 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 could continue indefinitely while the program waits for the user to click a button labeled
Quit. However, if a program isn't working correctly, one bug you'll run into during testing is a loop that cannot be stopped. This bug is called an infinite loop because the program will loop happily forever. If one of the Java programs you run from the command line is stuck in an infinite loop, press Ctrl + C.

Quiz

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

Questions

What must be used to separate each section of a for statement?

(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. When it comes to borrowing a car from your father, what lesson did you learn during this hour?

(a) Don't even think about it.
(b) Speak softly and carry a big stick.
(c) It's better to beg forgiveness than to ask permission.

Answers

b. Commas are used to separate things within a section, but semicolons separate sections.

2.
a. The
break statement ends a loop entirely, and continue skips to the next go-around of the loop.

3.
c.

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 Repeat program so that it uses a for loop instead of a while loop and compare the efficiency of each approach.

Write a short program using loops that finds the first 400 prime numbers.



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 848
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved