Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

More 2D Array Examples

A couple of examples which need rounding out to be of any practical use.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

All arrays have a public length field which holds the number of items.

Loop to set up the Button panel.

Buttons can also be associated with action command Strings which we can then use in actionPerformed - previously we have used named Buttons.

 

 

 

 

 

 

 

SL Mastery aspect complex selection statements.

 

 

Our old friend the if else chain .

Although not stricly neccessary, we add a + sign to the end to show the user that the add key was pressed.

Here we add an err symbol.

 

The line is used to indicate that the sum is being displayed next.

In a dossier we could document these as " user-friendly features ".

 

 

 

 

Check the string.

 

 

Not much can go wrong since the numerals are entered via the pad, however, two or more decimal points could be entered.

We still want to trap this error rather than letting the program crash.

 

 

 

 

 

 

 

 

 

 

Source code: WordSquare.java

 

 

 

 

 

 

2D Button array

 

 

 

 

 

 

 

 

 

A different starting letter could be chosen.

substring(int st, int ln) is a method of the String Class taking ln letters starting at st . See JETS pages on Strings.

 

 

Set it up so the increment operation is active initially.

 

 

 

SL Mastery Aspect: Nested Loops (always needed to deal with 2D arrays)

e.getSource() works with Button elements too.

indexOf(substring) returns the element of the string where substring starts (if any). see JETS String page .

 

 

We are moving on to the previous/next character in the ALLOWABLE String. So we check to see if we reached the start/end and wrap around.

These buttons just set whether we travel forward or backward through the ALLOWABLE String.

If you have followed the course this far, you have almost all the tools you need to complete a successful SL dossier.

Sorting and searching are useful topics, followed by simple file-handling; then you are ready to go.

On the page: [ cash register | word squares ]

Cash Register

In Java the arrays may be of simple (primitive) data types or of other objects such as buttons, text fields and so on. A common example might be to have a keypad which is useful in quite a few applications such as the following CashRegister Class:

A keypad might be a useful object in many different applications.

 

Source code: CashRegister.java


import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/**
* This class demonstrates an arrays of objects (Buttons and Strings)
* It's a very simple cash register class.
*
* It also demonstrates use of a panel to create a grid of buttons
*/

public class CashRegister extends Applet implements ActionListener
{
   TextArea display = new TextArea(8, 20);  
// register display area
   String current = new String("");        
// current string in the display
   double sumSoFar = 0d;                   
// sum of numbers entered so far

  
// Labels for the register buttons
   String [] btnLabels = { "1", "2", "3", "Add",
                           "4", "5", "6", "Clear",
                            "7", "8", "9", "Sum",
                            "0", "."                  };

   // Notice that arrays can be initialised with values when they are declared
   // rather than be given a size; in this case the size is implied.

  /**
   * Method to set up the display
   */

   public void init()
   {
     int nButtons = btnLabels.length;  
// number of buttons in the display
     add(display);                    
// the text area
     Panel keypad = new Panel();      
// put the buttons in a panel
     keypad.setLayout( new GridLayout(4, 4) );  
// lay them out in a grid
     Button [] keys = new Button[nButtons];    
// Array of buttons

    for (int i = 0; i < nButtons; i++ )        // for each label
     {
       keys[i] = new Button(btnLabels[i]);      // create a button
       keypad.add( keys[i] );                   // add it to the panel
       keys[i].addActionListener(this);         // set listener
       keys[i].setActionCommand(btnLabels[i]);  // and associated command
     }
     add(keypad); // add the pad
   }
   /**
   * actionPerformed, as ever, carries out the main processing
   * based on the Button's which are pressed.
   *
   * @param e carries information about the event that generated the call
   */

   public void actionPerformed(ActionEvent e)
   {
     // a numeric key (0-9) adds the number to the current string
     // the . key adds a decimal point
     // the Add key sums in the last entry and starts a new line
     // the Sum key prints the sum so far and clears the sum to zero
     // the Clr key clears the current entry

    String command = e.getActionCommand();  // action string - set in init()
     char com = command.charAt(0);           // get first character

    // see if the character is part of a number:
     if ( (com >= '0') && (com <= '9') || (com == '.') )
     {
       current = current + com;   // if it is append to the current String
       display.append("" + com);  // and to the display
     }
     else
     {
       // check here for function buttons
       if ( com == 'A') // Add this entry into the sum
       {
         display.append(" +\n");      // start a new display line
         addThis(current);            // helper method to add to sum
         current = "";                // re-set current String to empty
       }
       else if (com == 'C')
       {
         current = "";                // clear the current String
         display.append(" - err\n");  // indicate in the display
       }
       else if (com == 'S')
       {
         display.append("\n-------------\n");     // draw a line
         display.append("" + sumSoFar + "\n\n");  // show the current sum
        
current = "";                            // clear the current String
         sumSoFar = 0.0;                          // reset the sum
       }
       // more functions could be added!
     }
   }

 /**
   * This method converts the current string and adds to sum so far
   * it gives an error if the number is incorrectly formatted
   *
   * @param The String to be converted and added to the sum
   */

   private void addThis(String s)
   {
     if (s == "")
     {
       display.append("empty string!\n");
     }
     else
     {
       try
       {
         sumSoFar = sumSoFar + Double.parseDouble(s);
       }
       catch ( NumberFormatException n )
       {
         display.append("Error, re-enter\n");
         current = "";
       }
     }
   }
}

Back to top

Exercises

Hopefully, the above example raises a few possibilities in your mind - an ATM machine and a calculator are the obvious ones.

You could also try to add a subtract option and perhaps a % key for calculating and adding sales tax.

A more interesting and challenging task is to create a Keypad Class (easier with just the numeric keys and a decimal point) which has a method to return the number entered. Perhaps you can find a way to disable the decimal key when it has already been used once when entering a number.


Another Array Example
You can have fun with this (yay!). Pretty limited I agree, but at least you aren't paying good money for it, are you?

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

/**
  * This Applet demonstrates the use of 2D arrays and some aspects of String
  * processing.
  *
  * A square of letters is provided, clicking on a square changes the letter
  * in the square either up or down the list of allowable characters.
  *
  * It could form a starting point for some entertaining games...
  */

public class WordSquare extends java.applet.Applet implements ActionListener
{
   static final int ROWS = 5; // number of rows in the word square
   static final int COLS = 5; // number of columns in the word square

  // The set of allowable characters in the alphabet
   static final String ALLOWABLE = "*abcdefghijklmnopqrstuvwxyz ,.";

  // When clicked, the square goes up one letter or down according to
   // the value in direction

   int direction = 1;

  Button square [][] = new Button[ROWS][COLS]; // button grid
   Button increment = new Button ("inc");       // increment letters
   Button decrement = new Button ("dec");       // decrement letters

 /**
   * This method initialises the Applet and sets up the display
   */

   public void init()
   {
     // a panel for the button grid
     Panel theSquare = new Panel();
     theSquare.setLayout( new GridLayout(ROWS, COLS) );

    // for each array element
     for (int c = 0; c < COLS; c++)
     {
       for (int r = 0; r < ROWS; r++)
       {
         int start = 0; // starting letter

        // take single letter from string of allowable characters
         square[r][c] = new Button(ALLOWABLE.substring(start, start+1) );
         theSquare.add( square[r][c] );        // add the element
         square[r][c].addActionListener(this); // add action listener
       }
     }
     add(theSquare); // add the button panel
     add(increment); // add the inc and dec buttons
    
add(decrement); // and listen for presses on them
     increment.addActionListener(this);
     decrement.addActionListener(this);

    increment.setEnabled(false); // disable the increment button at the start
   }

   /*
   * This method listens for the Button presses and processes them
   *
   * @param the Button which caused the method to be executed
   */

   public void actionPerformed(ActionEvent e)
   {
     for (int c = 0; c < COLS; c++)
     {
       for (int r = 0; r < ROWS; r++)
       {
         // find out which element was clicked
         if (e.getSource() == square[r][c])
         {
           // get the current letter value from the button label and
           // work out what the next one should be.

           int start = ALLOWABLE.indexOf( square[r][c].getLabel() );
           start = (start + direction);

          // check to see if we went out of range
           if (start >= ALLOWABLE.length())
           {
             start = 0;
           }
           if (start < 0)
           {
             start = ALLOWABLE.length()-1;
           }
           // set the label to the new letter
           square[r][c].setLabel(ALLOWABLE.substring(start, start+1));
         }
       }
     }
     // check for a press on increment/decrement buttons
     if (e.getSource() == increment)   // increment clicked
     {
       increment.setEnabled(false);    // disable it
       decrement.setEnabled(true);     // enable the decrement button
       direction = 1;                  // set direction up
     }
     if (e.getSource() == decrement)   // decrement clicked
     {
       increment.setEnabled(true);     // similar process
       decrement.setEnabled(false);
       direction = -1;                 // except direction down
     }
   }
}

 

Back to top

Related: [ Java home | Previous: Chomp | Next: Parallel arrays ]

2D arrays are not needed in the dossier but are on the syllabus so could be asked in an examination question.

 


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand;
This page was last modified: May 31, 2009