Вы находитесь на странице: 1из 8

hapter

While Loops
While Loops:
A while loop is a control structure that is used when you need to repeat one or more
statements. Remember a for loop is an example of a count-controlled loop. A while loop
can either be a count-controlled loop or an event-controlled loop.
Here is the format of a while loop:
initialize loop-control variable
while (loop-control variable is not at some value)
{
statements to be repeated are written here including a statement
that can change the loop-control variable
}

Count-Controlled While Loops:


Here is an example of a count-controlled for loop:
int count;
for(count = 1; count <= 5; count++)
{
System.out.println(count);
}

Here is an example of a count-controlled while loop:


1

int count = 1;

2
3
4
5
6

while(count <= 5)
{
System.out.println(count);
count++;
}

When using a while loop, you must initialize the counter variable before the beginning of the
loop (line 1). The Boolean expression is tested (line 2). If it is true then the statements inside the
curly braces are executed. If it is false, the while loop is skipped. Inside the while loop
statements, the counter variable is incremented (line 5).

Java-Jive

kweiser 10/03- 06/04


Page 88

Questions:
1. Trace:
int count;
for(count = 2; count <= 6; count++)
{
System.out.print(count);
}

2. Trace:
int count=5;
while (count > 0)
{
System.out.print(count);
count--;
}

3. Write a for loop that sums all the integers from 1 to 100

4. Write a while loop that sums all the integers from 1 to 100

Lab # 68:
Modify Lab 51 so that it uses a while loop instead of a for loop.

Lab # 69:
Modify Lab 55 so that it uses a while loop instead of a for loop.
Java-Jive

kweiser 10/03- 06/04


Page 89

Event-Controlled While Loops:


An event-controlled loop will be repeated until some event happens. For instance you could
ask the user to enter test scores or a -1 when finished. This way the user doesn't have to tell
you in advance how many tests have been taken. The value the user enters when finished is
called a sentinel.

int score;
System.out.print("Test score (-1 to end): ");
score = input.readInt();
while(score != -1)
{
// process the score
System.out.print("Test score (-1 to end): ");
score = input.readInt();
}

Processing the score might involve counting the scores, summing the scores, or both.

Lab # 70:
Modify lab 55 again (or lab 69) again so that it calculates the average and total of test grades.
The program will read grades from the user until the user inputs -1. Don't count the 1 in the
number of grades or in the sum of the grades.
Sample run:

Requirements of this program:

YOUR TEST AVERAGE


Test
Test
Test
Test
Test

grade
grade
grade
grade
grade

(-1
(-1
(-1
(-1
(-1

to
to
to
to
to

stop) = 96
stop) = 87
stop) = 100
stop) = 91
stop) = -1

The program output should look


similar to the run at the left.

The student's average should be


printed to 3 decimal places.

Show three different runs.

The total of your tests is 374


Your test average is 93.500

Java-Jive

kweiser 10/03- 06/04


Page 90

Lab # 71:
Modify Lab 58 to work for a class of any size. Ask the user to keep entering grades or enter the
letter "Z" to stop. Dont count the "Z" in the number of grades.
Sample run:
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter

a
a
a
a
a
a
a
a

grade
grade
grade
grade
grade
grade
grade
grade

(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,

5 students passed:
2 students failed:

or
or
or
or
or
or
or
or

Z
Z
Z
Z
Z
Z
Z
Z

to
to
to
to
to
to
to
to

stop):
stop):
stop):
stop):
stop):
stop):
stop):
stop):

71.43%
28.57%

A
D
C
A
F
F
B
Z

Requirements of this program:

The program output should


look similar to the run at the
left.

Percents should be accurate


to 2 decimal places.

Show three different runs.

Error Traps:
Sometimes the user doesn't enter a correct value. For instance, if you asked the user for his
birth month, he might think you said birth year and enter 1988. If the user's birth month were to
be used in some calculation, the rest of your program would not work correctly. You can trap
errors like these by putting an error trap in your program.
int month;
System.out.print("Enter your birth month: ");
month = input.readInt();
while((month < 1) || (month > 12))
{
System.out.println("/nERROR/n");
System.out.print("Enter your birth month: ");
month = input.readInt();
}
System.out.println ("\nYour birthday is in month # " + month);
// Calculations that happen here will work with
// a valid birth month.
Sample run:
Enter your birth month: 1988
ERROR
Enter your birth month: -53
ERROR
Enter your birth month: 4
Your birthday is in month # 4
Java-Jive

kweiser 10/03- 06/04


Page 91

Error traps make your programs more robust. A robust program is less likely to crash or
produce nonsense results due to bad data.

Lab # 72:
Modify Lab 70 to trap any user input errors for test scores over 100 or less than 0.
Sample run:

Requirements of this program:

YOUR TEST AVERAGE


Test grade (-1 to
Test grade (-1 to
ERROR. Test grade
ERROR. Test grade
Test grade (-1 to
Test grade (-1 to
Test grade (-1 to

stop) = 96
stop) = 187
(-1 to stop) = -87
(-1 to stop) = 87
stop) = 100
stop) = 91
stop) = -1

The program output should look


similar to the run at the left.

The student's average should be


printed to 3 decimal places.

Show three different runs, each with


user data errors.

The total of your tests is 374


Your test average is 93.500

Lab # 73:
Modify Lab 71 to trap user input errors for grades.
Sample run:
Enter
Enter
Enter
Enter
ERROR
Enter
ERROR
Enter
Enter
Enter
Enter
Enter

a
a
a
a

grade
grade
grade
grade

(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,

or
or
or
or

Z
Z
Z
Z

to
to
to
to

stop):
stop):
stop):
stop):

A
D
C
E

Requirements of this program:

The program output should


look similar to the run at the
left.

Percents should be accurate


to 2 decimal places.

Show three different runs,


each with user data errors.

a grade (A,B,C,D,F, or Z to stop): Q


a
a
a
a
a

grade
grade
grade
grade
grade

(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,
(A,B,C,D,F,

5 students passed:
2 students failed:

or
or
or
or
or

Z
Z
Z
Z
Z

to
to
to
to
to

stop):
stop):
stop):
stop):
stop):

A
F
F
B
Z

71.43%
28.57%

Lab # 74:
You deposit $2500.00 in a new super Certificate of Deposit (CD) at your bank. Write a program
to calculate how many years it will take for your CD to be worth $5000.00 or more, if it pays 4%
interest compounded annually.
Requirements of this program:

There is no input.

One run is sufficient.

Java-Jive

kweiser 10/03- 06/04


Page 92

Lab # 75:
An interesting problem in number theory is sometimes called the bracelet problem. This
problem begins with two single-digit numbers. The next number is obtained by adding the first
two numbers together and saving only the ones-digit. This process is repeated until the
necklace closes by returning to the original two numbers. For example, if the starting numbers
are 1 and 8, 12 steps are required to close the bracelet.
Sample Run:
BRACELET PROBLEM
Enter a 1-digit number: 1
Enter a 1-digit number: 8
1 8 9 7 6 3 9 2 1 3 4 7 1 8
It took 12 steps to close the bracelet.

Requirements of this program:

The program output should look similar to the run above.

Three different runs are required

Lab # 76:
Add error traps to lab 75.

Lab # 77:
Write a "smart" program that plays a guessing game where the computer tries to guess a
number picked by the user. The program asks the user to think of a secret number and then
asks the user a sequence of guesses. After each guess, the user must report whether it is too
high, too low or correct. The program should count the guesses. (HINT: Have the computer
maintain highestPossible and lowestPossible variables, and always have the computer
guess half way between the two.)
Sample Run:
Think of a number between 1 and 100.
Is
Is
Is
Is

the
the
the
the

number
number
number
number

50
25
13
19

(Correct,
(Correct,
(Correct,
(Correct,

Low,
Low,
Low,
Low,

High)?
High)?
High)?
High)?

H
H
L
C

It took me 4 guesses to find 19.

Requirements of this program:

The program output should look similar to the run above.

Three different runs are required

Java-Jive

kweiser 10/03- 06/04


Page 93

Lab # 78:
Add an error trap to lab 77.

Lab # 79:
The integer 36 has a peculiar property--it is a perfect square, and is also the sum of the integers
from 1 through 8. The next such number is 1225, which is 352, as well as the sum of 1 through
49. Find the next number that is a perfect square and is also the sum of the series 1..n.
Requirements of this program:

There is no input.

One run is sufficient.

Java Vocabulary:
1.

while loop

2.

count-controlled loop

3.

event-controlled loop

4.

sentinel

5.

error trap

6.

robust

More Review Questions:


Trace:
5.

6.

int count = 3, num = 3;

int count = 10, num = 5;

while (count < 5)


{
count++;
num+=count;
System.out.print(num);
}

while (count < 20)


{
count++;
num+=count;
System.out.println(count +
" " + num);
}

System.out.println(Done!);
System.out.println("No more!");

Java-Jive

kweiser 10/03- 06/04


Page 94

7.

8.

int count = 0, num = 20;

int count = 0, num = 20;

while (num < 70)


{
if (count%2==0)
{
num+=10;
}

while (count < 6)


{
if (count%2==0)
{
System.out.print (num);
num+=10;
}
count++;
}

count++;
}
System.out.println("count = " +
count);
System.out.println("\nnum= " +
num);

Write a program:
9. Write a program that asks the user for a score (0 to 100 points) and reports his/her
grade. The scale should be: 90-100 = A; 80-89 = B; 70-79 = C; 60-69 = D; 59-below =
F. The program should end when the user enters a (-1). Assume that the user will not
enter an incorrect value. The output should look like:
Enter your
Your
Enter your
Your
Enter your
Your
Enter your

score: 72
grade = C
score: 92
grade = A
score: 65
grade = D
score: -1

10. Write a program that asks the user to enter a number divisible by three. If the user
enters an incorrect value, print an error message and ask again. Continue asking for a
correct value until the user enters a value divisible by 3. Then print out a statement
letting the user know what correct value s/he entered.
Enter a number divisible by 3:

That is an error.
Enter a number divisible by 3:

10

That is an error.
Enter a number divisible by 3:

-2

That is an error.
Enter a number divisible by 3:

24

The number you entered is 24.

Java-Jive

kweiser 10/03- 06/04


Page 95

Вам также может понравиться