Chapter 5

!

Java Language Basics





Up to this point, our lablets have produced user interfaces that look great on the screen, and even look like they might be easy to use. Unfortunately, we haven't been able to use them to do anything. That, of course, was due to the fact that we had not yet written Java code to produce and control the behavior of applets, other than those statements required to draw and place interface elements on the screen. In this chapter we will examine more closely the basic statements that are the building blocks of Java programs, many of which we've seen already, but haven't considered in any detail. We'll experiment with, for example, some of Java's built-in data types and operators, its String class, a variety of assignment and selection statements, and the issue of visibility to discover why our applets are written as they are.
The lablet for this chapter simulates a simple soda machine, and does so in behavior as well as appearance. You insert coins and select a brand by clicking buttons. The machine lets you know when it dispenses a drink, returns change when asked to do so, and even indicates when it is out of a certain brand. In short, this program uses Java statements to produce our first truly interactive program.


Lab Objectives

In this lab, you will:
 o

Run and experiment with the SodaPop lablet to see how it uses a variety of statements to produce realistic behavior.

 o

Modify SodaPop to introduce some errors related to the program's use of Java's predefined data types and its rules for visibility.

 o

Extend the soda machine's performance by modifying the program's existing methods, and adding new classes.

Exercises

  1. The SodaPop lablet should be pretty easy for you to use, assuming that you've used a soda machine before. The only difference between using our lablet and using the real thing (and it's a big difference if you're thirsty!) is that ours is a virtual machine. You "insert" coins by clicking on buttons and drinks are "dispensed" by means of a message in a text field. You get the idea.

    1. Run SodaPop now. Use the applet to insert combinations of coins, buy a lot of sodas, and return change. What happens when you try to buy more than five colas?
      Answer:  


    2. Let's see now how the behavior of the program is governed by its code. What follows is an abbreviated version of the source code of the SodaPop applet. In each of the text fields in the listing, place a comment of your own, describing what the line in question does.
       
      . . .
      
      public class SodaPop extends Applet
      {
          . . .
          
          public void init()
          {
              . . . 
      
      What do the following two lines do?
      Answer:  
              cost = 75;
              numberColas = 5;
          }
          
          public void paint(Graphics g)
          {
              . . .
          }
          
          . . . 
          
          public void processDimeButton()
          {
              display.setText("Dime inserted...");
      
      What's going on in the next line?
      Answer:  
              amount += 10;
          }
          
          . . .
          
          public void processReturnButton()
          {
              String amountString;
      
      What is the purpose of the next two lines?
      Answer:  
              int dollars = amount / 100;
              int pennies = amount % 100;
      
      Why are we testing whether pennies is less than 10?
      Answer:  
              if (pennies < 10)
                  amountString = new String("$" + dollars + ".0" + pennies);
              else
                  amountString = new String("$" + dollars + "." + pennies);
              display.setText(amountString + "returned.");
      
      What is the purpose of the next line?
      Answer:  
              amount = 0;
          }
          
          public void processColaButton()
          {
              if (amount >= cost)
              {
                  display.setText("COLA dispensed!!!");
      
      What do the next two lines do?
      Answer:  
                  amount -= cost;
                  numberColas--;
              }
      
      What's the purpose of the following statement?
      Answer:  
              if (numberColas <= 0)
              {
                  choices.bCola.setEnabled(false);
              }
          }
          
          public void processDietButton()
          {
      
      What are we testing here, and why?
      Answer:  
              if (amount >= cost)
              {
                  display.setText("DIET dispensed");
                  amount -= cost;
              }
          }
      

  2. We'll modify SodaPop now to produce some common errors and simple changes in its behavior. For each of the following edits, use the original version of the lablet as your starting point. In the space below each change, describe the error or behavior change you noted and explain why the error or change was produced.

    Reminder: an important part of doing any modifications to a program is, in the words of Lynn Stein, to be able to predict the results of your change, observe what actually happens, and explain what caused the change.

    1. Change the statement in method init() that reads
      cost = 75;
      to read
      cost == 75;
      Result:


    2. Change the statement in method processQuarterButton that reads
      amount += 25;
      to read
      amount = amount + 25;
      Result:


    3. Change the statement in the processQuarterButton method that reads
      amount += 25;
      to read
      amount = 25;
      Result:


    4. Change the declaration in method processReturnButton that reads
      int dollars = amount / 100;
      to read
      float dollars = amount / 100.0;
      Result:


    5. Change the condition in the if statement in method processDietButton from
      if (amount >= cost)
      to
      if (amount => cost)
      Result:


    6. Change the statement in function processColaButton that reads
      choices.disable("COLA");
      to read
      disable("COLA");
      Result:


    7. Change the header of the ChoicePanel constructor from
      public ChoicePanel(Listener theListener)
      to
      private ChoicePanel(Listener theListener)
      Result:



  3. Now let's make some fairly direct modifications and extensions to SodaPop.

    1. The paint method of the SodaPop class uses entirely too many "magic numbers"--literals like 20, 40, 60 that don't give the reader much of a clue about their purpose. Most of these numbers are just multiples of the y-spacing that are used to lay out the letters in the logo. Tidy up the paint method by declaring a local constant final int SPACING = 20 inside the paint method, and using suitable multiples to eliminate all of the magic numbers.

    2. Add a fifth soda type. As usual, think before you start typing. Take a close look at the source code and identify all the locations that deal with the soda buttons, for instance. You should find one in class SodaPop, three in class ChoicePanel, and one in the Listener class.

    3. Extend SodaPop so that in addition to the coins it can currently process, it also accepts dollar bills (or whatever paper currency is appropriate in the country where you live).

    4. At present, our machine only returns change when the coin button is pressed. On most "real" soda machines, any extra change is automatically returned at the completion of a sale. Change SodaPop so that it acts more like a real machine.


  4. There are many natural extensions we could make to our applet to enhance its efficiency and functionality. Try each of the modifications below, testing each (of course) as you go.

    1. The original applet keeps track of how many colas are in the machine and indicates when there are no colas left by disabling the cola button. Extend this feature to all of the drinks.

      Hint: Judicious use of the Copy/Paste facilities of your text processor will make this a very simple task.

    2. The organization of the program is, perhaps, somewhat less logical than it should be. In particular, it might be better to have the amount instance variable be part of the MoneyPanel class, since that's where all the money-related buttons are. If we do that, though, the applet's process... methods will not have access to amount. That would mean that we would have to provide MoneyPanel with methods that get the amount and change the amount (adding some money in response to a coin insertion and subtracting some money in response to a sale). Do this, moving amount from SodaPop to MoneyPanel and adding two new methods, int getAmount() and void changeAmount(int change), along with their appropriate calls in SodaPop.

    3. Add another display, somewhat like the one on the right, that shows the current amount of money that has been fed into the soda machine. This will require some careful thought about design. Ideally, the display should be part of the MoneyPanel class, since it's logically related to the other parts of that class. However, making the new display a private part of the MoneyPanel class would introduce more complications than we want, if you consider the problems of communication to the display.
      Instead of completely rewriting the MoneyPanel class, make a new class, MoneyDisplay that extends TextField and has a constructor and a method void update(int money) that causes it to display the amount given by the parameter. You can steal some of the code from processReturnButton. Add an instance of this class to the applet, along with the appropriate method calls. While you're making this modification, you might want to change some of the behavior of the old display, since some of its messages are now redundant.

Postlab Exercises

  1. Make the following two changes to the lablet.

    1. Once we give our machine the ability to accept bills, we should make it more realistic by having it reject half the bills inserted. This can be accomplished by keeping a counter instance variable that is incremented each time a bill is inserted and rejecting the bill (with a suitable message) every time the counter is, say, even. Remember, you can check whether a variable, myCount, is even by using an if statement like if ((myCount % 2) == 0).

    2. Implement an "exact change" feature by making all change from a small pot (initially $5.00, for example) and turning on an indicator when there's no money left in the change pot.


  2. Design and implement a simple income tax form. You can design your own or use an existing form as a model. Your form should provide fields for the user to enter information about such things as income, number of deductions, and the like. Then, when a "Compute" button is pressed, some calculations (suitably complicated and unfair, as on real tax forms) are performed and the total tax owed is displayed. To handle the button press, you can use this lablet as a model, or refer to the event handling we discuss in Chapter 6.

Last updated: December 4, 1998
Rick Decker
Department of Computer Science
Hamilton College
Clinton, NY 13323