== Lists ==
Arrays are used to store LISTS of data.
String[] weekdays = {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
You can access (retrieve) an item from the list by using the index (number) of the location.
output("The first day of
the week is " + weekdays[0]);
output("The last
day of the week is " + weekdays[6]);
You can search for an item by using a for loop and comparing
your target to each item in the list, one at a time.
You can use the
index number to check for neighbors in the list - items before
and after.
String target = "Wed";
for
(int d = 0; d < 7; d++)
{
if
( weekdays[d].equals(target) )
{
output("That
is day # " + d);
output("The
next day is " + weekdays[d+1] );
output("The
day before is " + weekdays[d-1] );
}
}
== Parallel Arrays ==
You can use two parallel arrays to match
up one piece of data with another.
For example, a user name and
a password. Then you can search for one item, and retrieve the
other.
String[] users =
{"Anna","Ed","Kim","Zeke"};
String[]
passwords = {"A1" , "B2", "C3", "D4"
};
String name = input("Type
your name");
String pw = input("Type
your password");
boolean okay = false;
for (int n = 0; n < 4; n =
n+1)
{
if ( name.equals(users[n])
)
{
if
(pw.equals(passwords[n]))
{
okay = true; }
}
}
if (okay == true) {
output("Welcome"); }
else {
output("Get lost"); }
Another example is a dictionary. That is nothing more than two
lists of matching words
in two different languages.
== Practice ==
(1) A small school has only 5 classrooms, with one teacher in each
classroom.
The classes are numbered 0,
1, 2, 3, 4. Write a program with the names
of
5 teachers in an array. It should have 2 buttons. The first button
inputs
a room number and prints the
name of the teacher in that room. The second
button
inputs the name of a teacher, and prints the room number of that teacher.
(2) Write a program that has an ENGLISH array and a GERMAN array.
The
program should contain 5 words in each array. It should have a button
for
translating English to German, and another for translating German to English.
(3) A businessman goes on business trips in foreign cities. He
must keep track of
how much he spends
each day on his hotel room. Write a program with an
array
containing 7 numbers (money) for the seven days of the week.
Make
a button that inputs a number (between 0 and 6) and prints the amount
of
money spent on that day.
(4) Add another array to #3 that contains the money spent each day
on food.
Change the program so that it inputs
the day number, and prints the amount
spent
on hotel, the amount spent on food, and the total money spent on both.
(5) Add another button to #4 that calculates the TOTAL money spent
for
the entire week on both food and
hotels.