An ARRAY is a list of data. For example, you could make a list of all the students who are absent from school today - similar to writing them on a sheet of paper. Like paper lists, an ARRAY has numbered "lines". Of course the numbering starts at 0, like all other computer stuff. Here is a sample program that contains a list of food items that could be ordered - like a menu.
import java.awt.*;
public class Meals extends EasyApp
{ public static void main(String[] args)
{ new Meals(); }
Button bOrder = addButton("Order Item",50,50,100,30,this);
String[] foods = { "Hamburger","Pommes","Sandwich","Salad" } ;
public void actions(Object source,String command)
{
if (source == bOrder)
{ order(); }
}
public void order()
{
String order = input("What do you want?");
boolean ok = false;
for (int x = 0; x < 4; x = x + 1)
{
if ( order.equals( foods[x] ) )
{ ok = true; }
}
if (ok == true)
{ output("You order will be served soon."); }
else
{ output("Sorry, we don't serve that - no food for you!"); }
}
}
/******************
The following command declares an ARRAY of String values.
String[] foods = { "Hamburger","Pommes","Sandwich","Salad"} ;
The square brackets [ ] mean this is an array.
The list of names is in curly braces { } .
An ARRAY is a NUMBERED LIST, like this:
0 : "Hamburger"
1 : "Pommes"
2 : "Sandwich"
3 : "Salad"
This means that there are actually 4 variables.
The command is the same as writing:
foods[0] = "Hamburger";
foods[1] = "Pommes";
foods[2] = "Sandwich";
foods[3] = "Salad";
The following command would display all 4 foods at once:
output(foods[0] + "," + foods[1] + "," + foods[2] + "," + foods[3]);
Another possibility is to use a loop:
for(int x = 0; x < 4; x = x + 1)
{ output( foods[x] ); }
The loop version displays only one food at a time.
(1) Add two more foods to the list : "Ice cream" , "Soup"
Make all necessary changes so the program still works correctly.
(2) Change the SEARCH loop (where it is trying to match ORDER)
so that the comparison is NOT case sensitive - e.g. "Hamburger"
or "hamburger" or "HAMBURGER" should all work correctly.
(3) Make a new button called BUY TOY. This allows the user to
order a toy, like "Barbie", "Ken", "Ball", ...
Make up 8 toys and put them in an array called TOYS.
(4) Add an array called PRICES that contains the prices for the FOODS.
This must be a double[] array. Change the order() method so that
wehn it finds foods[x] matching order, then it displays prices[x].
(5) Make two arrays called goodFoods and badFoods. When the user
places an order, the program should respond with
one of the following:
That is a GOOD food.
or
That is a BAD food.
or
We don't serve that food.
*******************/