In class today we covered while loops and for loops.
The while loop is simpler, but it does less. Here is an example:
int sum = 0; int i = 0; while (i < 10) { sum = sum + i; i++; }
You have to be careful when you write a while loop, because it will keep looping as long as the test at the top is true. Which means that if you're not careful, you could end up with a loop that loops forever, which means your program will appear to freeze.
For example, the following while loop never ends (which is bad):
int sum = 0; int i = 0; while (i < 10) { sum = sum + i; i--; // Oops! Variable "i" is decreasing, instead of increasing. // This will lead to an endless loop. }
One of the problems with while loops is that the different parts of the control structure are scattered in too many different places in your code. For this reason, Java provides another control structure, the for loop, where all of the things that control the loop are in the same place.
Here is what that while loop would look like if it were a for loop:
int sum = 0; for (int i = 0 ; i < 10 ; i++) sum = sum + 1;Look at the line for ( ... ) above. The three bits of code inside the parentheses are the initializer, test and iterator. The initializer sets the iterating variable to its initial value when the loop starts (in this case, it sets i to 0). The test checks, before each iteration of the loop, whether to continue looping or not (in this case, making sure i is still less than ten). The iterator changes the looping variable (in this case, incrementing i).
For your homework due on Thursday I'm not asking you to use loops, but it's good to get started on these concepts.
Then in class today we showed how to make your own object classes.
In particular, we made an object class called MyButton
,
which has some data fields and a single method.
The code for that is in file feb-22-class.zip.
Important note:
When you open feb-22-class.zip you will see that the
index.html file shows you how to link to the actual
java source files (in this case
BufferedApplet.java
,
MyButton.java
and
applet6.java
).
You need to put similar links in your index.html file for the assignment
that you will hand in this coming Thursday, because
The grader needs to see your source code.