Array Notes and Example
Sometimes it is necessary to deal with hundreds of different variables. For example in a school marks program each student might have 50 different marks throughout the year.
Does this mean we need a separate integer variable for each students marks. Each student would have 50 variables plus a total variable and a percent variable(Yikes)
There is a better way to handle variables. We could make a variable called student1 that has 50 locations or "mail slots" as I like to call them that can hold numbers
Declaring an array
You declare a variable like this
int[] numbers;
numbers = new int[50]
This essential gives us a variable called numbers that can hold 50 different numbers.
You can assign values to the array as follows
numbers[0] = 5;
numbers[1] = 11;
numbers[2] = 15;
numbers[3] = 2351;
You can also use float,double and or string varialbes with the array
In my example I am going to use an array to the handle calculations involved with the running of a huge oil filled supertanker. Wow sounds exiting eh. Lets take a look
SuperTanker Example
This Supertanker has 8 main oil filled tanks each of which can hold 100000 metric tons of crude oil.
We don't want the tanker to sink, capsize or otherwise spill its oil. Therefore the supertanker must be balanced properly. The amount of oil on the port side has to be within 50000 tons of the oil on the starboard or the tanker will capsize.
In addition even though the tanks can hold 100000tons of oil the entire ship can only carry 600000 tons of oil. Each tank cannot be fully filled.
When the check tank button is filled we want totals for port, starboard and the overall total to be calculated. In addition we want warning messages to appear if the tanker is overfilled or out of balance.
Step 1 Setting up the user interface
These textboxes are control arrays They have been cut and pasted.
In order they are text1(0), text1(1), text1(2) and text1(3)
And underneath text2(0), text2(1), text2(2) and text2(3).
This is a label control array done by cutting and pasting the label.
The rest of the form is set up with standard textboxes and labels.
Step 2 Declaring the Arrays
Step 3 Checking the Tanks
Just as we have always done in calculation type programs there are three phases to the coding.
Phase 1 Get the info into the variables
Notice how the for loop makes it possible to get the values from the text box into the array variables with a minimun amount of coding.
If we one likes pain, we could have done it the old way
Porttank(0)=Text1(0).text
Porttank(1)=Text1(1).text etc… etc.. etc..
I like the for loop way much better. Especially if the tanker had 50 port tanks.
Phase 2 Doing the calculations
Since the value of x changes when the loop is run. Its just like adding
Porttotal = porttank(0)+porttank(1)+porttank(2)+porttank(3)
Phase 3 displaying the answers
'
This is pretty simple
Checking to see if the tanker is ok( filled properly)