Click Counter

Chapter: Click Counter

        
             
            Your browser is ignoring the <APPLET> tag!      
        

Keep clicking in the applet area above. See what the program is doing? We'll develop the code for this in a moment. First though, we need to know about numbers.

Numbers are like objects in Java, and if you want to use them in ways where they might change (be mutable):

Numbers are unlike objects in Java, because:

To declare a number called count that will be used to count clicks, you can declare

  private int count;
to indicate that count will be used to hold whole number (not fractional) values. If you want to simultaneously initialize the value of count to 0, you can declare:
  private int count = 0;

In order to change the value of count you can use an assignment statement such as

  count = count + 1;
that assigns to count a value that is the existing value of count increased by adding 1.

If you want to have numbers in your program that will not change, a good way to do it in Java is to declare them to be static and final. For example, the location for the displayed text in the above applet is specified by

        private static final int DISPLAY_X = 150;
        private static final int DISPLAY_Y = 200;

Why do you think we do this? What is an alternative?

Here is the code for the above applet.


rhyspj@gwu.edu