Name: ________________
ID:_______________
Required files:
/**
* A collection of methods that use Java's looping mechanisms.
*
* @author Samuel A. Rebelsky
* @version 1.0 of August 1998
*/
public class WhileExamples {
/**
* Print the numbers from 1 to n
*/
public void countTo(int n, SimpleOutput out) {
int i = 1;
while (i < n) {
out.println(i);
i = i + 1;
} // while
} // countTo(int n, SimpleOutput out)
/**
* Keep reading passwords until you read the supplied password.
*/
public void readPass(SimpleInput in,
SimpleOutput out,
String pass) {
String name = "";
while (!name.equals(pass)) {
out.print("Enter the password: ");
name = in.readString();
// If the password was entered correctly, the loop
// should terminate.
out.println("'" + name + "' was not a valid password.");
} // while
} // readPass(SimpleInput, SimpleOutput, pass)
} // class WhileExamples
Step 1.
Make a copy of WhileExamples.java. That class includes
a countTo method.
What should this method do (in general)? What should the method do
if called with a value of 10 for n. Do you
think that countTo will work correctly? Why or why not?
Step 2.
Write a class, TestLoops, that includes a main
method that calls countTo with 10 as the value
for n. Record the results. Were these what you expected?
Step 3.
If countTo did not have the correct results, explain why
not. If countTo did have the correct results, can you
envision any simple errors one might have made?
Step 4.
Add a count(int from, int to, SimpleOutput out) method to
WhileExamples. This method should count all the numbers
beginning with from and ending with to.
Test your method. Enter the code for your method here.
Step 5.
Read the code for the readPass method from WhileExamples.java. This
code has a small logical problem. What do you think the
problem is?
Step 6.
Update your main method to call readPass
with a password of Hello. Run your program using
passwords of hi, hello, and Hello.
Record the results.
Step 7.
Based on those results, what is the logical problem in readPass?
Step 8.
Update readPass so that it gives correct output. Summarize
the changes.
Required files:
SimpleDate.java, as updated in the previous lab.
Step 1.
Add a daysInMonth(int m) method to
SimpleDate. Test your code. Enter your code for the
method here.
Step 2.
You may have observed that both of the versions of
daysInMonth assume that you want to use the current year.
Add a daysInMonth method that takes both month and year as
parameters. Test your code. Enter your code for the method here.
Step 3.
Update the original daysInMonth and the
daysInMonth you created in Step 1 to use the
daysInMonth you created in Step 2. Enter the revised code
for your methods here.
Step 4.
Using the ideas from above, add a daysUntilStartOfMonth
method for the SimpleDate class. This method should
compute the number of days until the beginning of the current month.
Test your code. Enter your code here.
Step 5.
Write a program that computes how many days there are before the start
of December in a non-leap year. You should use the SimpleDate
class and the corresponding methods you developed earlier.
Step 6.
Using the daysUntilStartOfMonth, add a dayOfYear
method to the SimpleDate class. This method should compute
the number of days from the beginning of the year until the current date.
Test your code and enter it here.
Step 7.
Using the updated SimpleDate class, determine on which
day of the year the following dates fall:
for loopsRequired code files:
/**
* Simple examples of Java's for loops.
*
* @author Samuel A. Rebelsky
* @version 1.0 of September 1998
*/
public class ForExamples {
/**
* Sum the squares of the numbers from 1 to n.
*/
public int sumSquares(int n) {
int sum = 0; // The sum of the numbers
int i; // A counter for the loop
for (i = 0; i <= n; ++i) {
sum = sum + i*i;
}
return sum;
} // sumSquares(int)
} // class ForExamples
Step 1.
Read the code for sumSquares from the class
ForExamples. What does the method do? Do you expect
that it will work correctly? Why or why not?
Step 2.
Using ForExamples,
write a program that reads in an integer, n, and prints the sum of
squares from 1 to N. For example, if you enter 3, it should compute
1*1 + 2*2 + 3*3 = 14 and print out 14. Enter your code for the program
here.
Step 3. Run your program on inputs of 1, 3, 5, 10, 20, 0, and -3. Record your results.
Step 4.
Add a sumCubes method to ForExamples. This
method should compute the sum of cubes of integers from 1 to n. Enter
your code for the method here.
Step 5. Run your program on inputs of 1, 3, 5, 10, 20, 0, and -3. Record your results.
Step 6.
Add a sumTo method to ForExamples. This
method should compute the sum of the integers from 1 to n. Enter your
code for the method here.
Step 7.
Did you use a for loop for step 6? If so, see if you can
rewrite it without using a for loop, while
loop, or recursive function calls. (The sum of 1+2+...+N is a
well-known formula; you should already know it. If not, you should find
it.)
Step 1.
Write a program that includes the following two lines. Print out the
values of i and j after the two statements.
(Note that i and j must be integer variables.)
Record the values.
i = 2; j = ++i + 3;
Step 2.
Write a program that includes the following two lines. Print out the
values of i and j after the two statements.
Record the values.
i = 2; j = i++ + 3;
Step 3. Did you get the same values in steps 1 and 2? Why or why not?
Step 4.
Write a program that includes the following two lines. Print out the
values of i and j after the two statements.
Record the values.
i = 2; j = i-- + 3;
Step 5.
Write a program that includes the following two lines. Print out the
values of i and j after the two statements.
Record the values.
i = 2; j = i-- + 3;
Step 6.
What do you think the value of i and j will
be after the following lines are executed. Why?
i = 2; j = i++ - i++;
Step 7. Execute the lines from the previous step and record the results. What do they suggest?
Optional applet experiment
Required files:
Step 1.
Make copies of
ConfigurableGreeting.java,
Rainbow.java, and
rainbow.html.
Compare ConfigurableGreeting.java (which you've used
in previous experiments) and Rainbow.java.
How are they similar?
How are they different?
Step 2.
Why do you think Rainbow.java includes the variables
changeRed, changeBlue, and
changeGreen?
Step 3.
Why do you think Rainbow.java includes the variables
horiz and vert?
Step 4.
Compile Rainbow.java and load the applet from
rainbow.html. Describe the output from the
applet.
Step 5.
The stated goal of Rainbow is to draw text in a rainbow.
Rainbox, however, does not
not appear to do so. Rather, it draws the text in a
single color. To draw the text in a rainbow of colors, we'll need to draw
the text multiple times, changing the color and position each time.
We'll start by adding a for loop. Replace the lines that read
paintBrush.setColor(new Color(redPart, greenPart, bluePart));
paintBrush.drawString(message, horiz, vert);
with the following for loop.
// Repeatedly draw the message in different colors and positions.
for (int step = 1; step <= steps; step = step + 1) {
// Draw the message in the current color at the current position.
paintBrush.setColor(new Color(redPart, greenPart, bluePart));
paintBrush.drawString(message, horiz, vert);
} // for(step)
What effect do you expect the change to have?
Confirm your answer by recompiling Rainbow and loading
the applet from rainbow.html.
You may also want to
consult the notes on this step.
Step 6.
We will now update the applet so that the message is printed
in a different space each time. Add the following lines to the
end of the for loop that you added in the previous step.
// Update the position.
horiz = horiz + 1;
vert = vert + 2;
What effect do you expect the change to have?
Confirm your answer by recompiling Rainbow and loading
the applet from rainbow.html.
Step 7.
As you may have noted, the result of the previous step is a somewhat
smudged version of the message, which makes it hard to read.
We can make it somewhat clearer by writing the message in black at the
end. Add the following lines after the for
loop.
// Draw the message a final time.
paintBrush.setColor(Color.black);
paintBrush.drawString(message, horiz, vert);
Test the appearance using both white and black. Which do you prefer?
Step 8.
We are now ready to start changing the color (something we would hope
to happen in a rainbow). In step 6, we changed horiz
and vert. In this step, we'll change
redPart, greenPart, and bluePart.
Choose an appropriate way to change each of the three (hint: use
changeRed, changeBlue, and
changeGreen).
Verify that your change works by recompiling Rainbow
and loading the applet from rainbow.html.
Summarize your changes here.
After you have recorded your answer, you may wish to consult the notes on this step for the recommended changes.
Step 9.
Currently, we have the for loop draw the message
twenty times. What do you expect to happen if we draw the message
forty times?
Confirm your answer by updating rainbow.html and then
loading the applet from rainbow.html.
You may also wish to
consult the notes on this step.
Step 10. As you may have noted, the difficulty with taking too many steps is that the color components eventually fall outside of the acceptable range (values between 0 and 255). We can account for this problem by checking the value and, if it's outside the range, either (1) stopping at the maximum/minimum value or (2) changing the way we change the color. We'll use the second technique.
Add the following lines to the for loop, after the
change to the color. (Also add corresponding lines for blue and
green.)
// Handle colors out of the range 0..255.
if (redPart < 0) {
redPart = 0;
changeRed = Math.abs(changeRed);
}
if (redPart > 255) {
redPart = 255;
changeRed = -(Math.abs(changeRed));
}
Recompile Rainbow and load
the applet from rainbow.html. In your own words,
explain what these new lines do.
Step 11. At present, our rainbow appears as a diagonal line. We might prefer it to appear as a curve (perhaps even in something resembling a rainbow shape). How might we make the rainbow curve?
Step 12. Delete the lines that read
horiz = horiz + 1;
vert = vert + 2;
Insert the following lines before the call to drawString
in the for loop in the paint method in
Rainbow.
// Determine the position.
horiz = 2*step;
int tmp = step-steps/2;
vert = 20+100*4*(tmp*tmp)/(steps*steps);
What do you think these lines do?
Confirm your answer by updating rainbow.html and then
loading the applet from rainbow.html. You may wish
to use 100 steps. You may also wish to consult the
notes on this step.
Optional applet experiment
Required files:
Step 1.
In many graphics applications, it is useful to be able to create a
regularly spaced grid of points. The applet given by
GridApplet.java is intended to do just that. Make
copies of
GridApplet.java and
grid.html. Compile
GridApplet and load the applet from grid.html.
Describe the output.
Step 2.
Describe, in your own words, how you might write an applet to create
that grid.
Do not read the code for GridApplet.
After recording your answer, you may wish to consult the notes on this step.
Step 3.
Consider the code for GridApplet. That code contains a
number of logical errors. Identify as many as you can. List them here.
Step 4.
Update grid.html so that it uses eight rows and eight columns.
Do not change GridApplet. Reload the applet using the
modified grid.html. Does the grid change? Why or why
not?
Step 5.
One reason you may have speculated that the grid doesn't change is
that the applet never consults the HTML file.
Add appropriate Java code so that GridApplet reads the
number of columns and rows from the HTML file. You should be able
to develop that code on your own. However, if you need help, you
may consult the
notes on this step.
Summarize the new code here.
Step 6.
Recompile GridApplet and load the applet using
grid.html. Do you get the appropriate number of
rows and columns? Why or why not?
After recording your answer, you may wish to consult the notes on this step.
Step 7.
Update the for loops to use the appropriate variables.
More particularly, replace the line that reads
for (int row = 1; row < 4; row=row+1) {
with
for (int row = 1; row < rows; row=row+1) {
Replace the line that reads
for (int col = 1; col < 5; col=col+1) {
with
for (int col = 1; col < cols; col=col+1) {
Recompile GridApplet and load the applet using
grid.html. Do you get the appropriate number of
rows and columns? Why or why not?
After recording your answer, you may wish to consult the notes on this step.
Step 8.
Update the for loops to use appropriate termination
conditions.
More particularly, replace the line that reads
for (int row = 1; row < rows; row=row+1) {
with
for (int row = 1; row <= rows; row=row+1) {
Replace the line that reads
for (int col = 1; col < cols; col=col+1) {
with
for (int col = 1; col <= cols; col=col+1) {
Recompile GridApplet and load the applet using
grid.html. Do you get the appropriate number of
rows and columns? Why or why not?
Step 9.
Update grid.html so that it draws ten rows and
five columns. Reload the applet using the modified grid.html.
Do you get the appropriate number of
rows and columns? Why or why not?
After recording your answer, you may wish to consult the notes on this step.
Step 10. As you may have noted, rows and columns seem to be reversed. Often problems like this happen because programmers nest their loops incorrectly. Update your code so that the columns loop is the outer loop and the rows loop is the inner loop. For example, you might write
// For each column ...
for (int col = 1; col <= cols; col=col+1) {
// Step through the rows, drawing the grid point at
// the current row/column.
for (int row = 1; row <= rows; row=row+1) {
...
} // for each row
} // for each column
Do you think this will fix the problem? Why or why not?
Confirm your answer by recompiling GridApplet and
reloading the applet with grid.html.
Step 11.
It seems that the problem does not have to do with the nesting of the
loops. What is the problem? If we look closely, we may notice that it
has to do with the fillOval command. That command makes
the vertical position (the first coordinate) dependent on the row, and
the horizontal position (the second coordinate) dependent on the column.
However, all points in the same row should have the same vertical
position, and all points in the same column should have the same
horizontal position. Replace the line that reads
paintBrush.fillOval(row*spacing, col*spacing, 3, 3);
with one that reads
paintBrush.fillOval(col*spacing, row*spacing, 3, 3);
Confirm that the applet now works correctly.
Step 12. After all that hard work, it's time for a little bit of fun. Add the following line before the line you just changed.
paintBrush.setColor(new Color(row*255/rows,128,col*255/cols));
What effect do you expect this new line to have?
Confirm your answer by recompiling GridApplet and
reloading the applet with grid.html.
Required files:
Step 1.
Make copies of
Bounce.java and
bounce.html.
Compile Bounce and load the applet from
bounce.html. Describe the output of the applet.
Step 2.
Update bounce.html to change the horizontal velocity to 9
and the acceleration to 2.
Reload the applet from the modified bounce.html.
What effect do the changes have?
Step 3.
Update bounce.html to change the number of repetitions to 10.
Reload the applet from the modified bounce.html.
What effect does the change have?
When you are done, restore the number of repetitions to 100.
Step 4.
Read the code for Bounce.java. In your own words, describe
what it does.
Step 5.
Add the following lines to the paint method of
Bounce, just before the call to fillOval.
int tmp = 200-200*step/repetitions;
paintBrush.setColor(new Color(tmp,tmp,tmp));
What effect do you expect these new lines to have?
Confirm your answer by recompiling Bounce and loading the
applet from bounce.html.
Step 6. As you may have noted, the ball does not yet bounce. In your own words, suggest how we might make the ball bounce.
Step 7.
If you ask a physicist, you may learn that when a ball bounces, its velocity
changes from downward to upward. You can simulate this change by reversing
the sign on horizVelocity. When do you do what? When the
ball reaches the bottom of the screen.
Replace the lines that read
// Update the speed.
vertVelocity = vertVelocity + acceleration;
with the following
// Update the speed.
if (vert > bottom) {
vertVelocity = -Math.abs(vertVelocity);
}
vertVelocity = vertVelocity + acceleration;
What effect do you expect these new lines to have?
Confirm your answer by recompiling Bounce and loading the
applet from bounce.html.
Step 8. Explain why we used
vertVelocity = -Math.abs(vertVelocity);
instead of
vertVelocity = -vertVelocity;
After recording your answer, you may wish to consult the notes on this step.
Step 9. As you may have observed, it is now possible for the ball to exit the right edge of the screen. Update your applet so that the ball bounces at both the right and left edges of the screen. Summarize your changes here.
After recording your answer, you may wish to consult the notes on this step.
[Front Door] [Introduction] [Code]
Copyright (c) 1998 Samuel A. Rebelsky. All rights reserved.
Source text last modified Mon Oct 25 16:30:42 1999.
This page generated on Tue Oct 26 15:37:07 1999 by Siteweaver.
Contact our webmaster at rebelsky@math.grin.edu