Академический Документы
Профессиональный Документы
Культура Документы
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
}
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
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
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:
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
Java-Jive
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
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
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:
stop) = 96
stop) = 187
(-1 to stop) = -87
(-1 to stop) = 87
stop) = 100
stop) = 91
stop) = -1
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
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.
Java-Jive
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.
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
Java-Jive
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.
Java Vocabulary:
1.
while loop
2.
count-controlled loop
3.
event-controlled loop
4.
sentinel
5.
error trap
6.
robust
6.
System.out.println(Done!);
System.out.println("No more!");
Java-Jive
7.
8.
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
Java-Jive