Bookstore - Items and Prices in Parallel Arrays

  Download Processing Source Code  

/**************************************************
Kim works in the school bookstore, selling pens, notebooks, etc.
They have prices written in a notebook.  When prices change 
they must cross out old prices - that's messy.  They want
a computer program that stores and displays prices.
Item names and prices are stored in PARALLEL ARRAYS.
***************************************************/

String[] items = {"pencil","pen","sharpie","notebook A","notebook B",
                  "eraser","tippex","usb stick","glue","tape"
                 };
               
float[] prices = { 0.75 , 1.50 , 1.20 , 1.90 , 2.50 ,
                   0.50 , 1.75 , 5.00 , 1.25 , 2.00  
                 };          
void setup()
{
  String name = "";
  do
  {
    name = input("Type the name of an item");
    float price = getPrice(name);
    if(price > 0)
    { output(name + " = " + price); }
    else
    { output(name + " was not found"); }
  } while(name.length() > 0);             // type nothing to quit
}

float getPrice(String name)           // search for name, return price
{                                     // the price is not case-sensitive
  for(int x=0; x < prices.length; x = x+1)
  {
    if(items[x].equalsIgnoreCase(name))    // not cases-sensitive
    {
      return prices[x];
    }  
  }
  return 0.00;
} 

public String input(String prompt)
{ return javax.swing.JOptionPane.showInputDialog(null,prompt); }

public void output(String message)
{  javax.swing.JOptionPane.showMessageDialog(null,message);  }

Parallel Arrays

An Array can only contain one type of data - a list of int values, or a list of float values, or a list of Strings.
It is NOT POSSIBLE to store both Strings and float values in a single array.  So if we wish to store
the names and the prices of various items, we need two lists, not just one.  In this example, we have
the items array for storing the names of items (Strings) and the prices array for storing the prices of the items.
It's important that the names and prices are "parallel", so if a name is in position 10, then the corresponding
price is also in position 10 - like this:

position
ITEMS
PRICES
0
pencil
0.75
1
pen
1.50
2
sharpie
1.20

The items and prices arrays are called parallel arrays.  If  we need to store more information, for example
the stock level (inventory number) of each item, we can create a third array - say inventory.

This enables a Java program to store data in a similar fashion to a spreadsheet table.

Programming Practice