The steps are
import java.awt.*; public class ArrayHandout extends java.applet.Applet { int MyArray[]; int MyArray_Size = 10; int xpos, ypos; int index; public void init() { MyArray = new int[10]; } public void paint(Graphics g) { g.drawString("Mouse at " + xpos + "," + ypos, 10,10); g.drawString("Index is " + index, 100, 10); for(index = 0; index < MyArray_Size; index++) { g.drawString("" + MyArray[index], 10, 10+index * 20); } } public void mousePressed(MouseEvent e) { index = e.getY() / 20; xpos = e.getX(); ypos = e.getY(); MyArray[index] = MyArray[index]+1; repaint(); } } |
|
The Source Code |
The applet running |
Normally, array memory is allocated in the init() function. Failure to allocate memory will cause your program to crash as it begins to run. This can be a difficult bug to detect, so be careful.To allocate memory for the array, you assign to the array the value of "new" when given the arguments of the type and the number. The type must be the same as when the array was declared. For example,
You also might want to give each element of the array in initial value. Normally this is done in the init() function. If you want each element to be zero or empty, then you need do nothing more. But if you want a different starting value, then you must assign to each element of the array this different value. For example
for(i = 0; i < lastnames_size; i++) { lastnames[i] = "Unknnown"; }
Find the largest element// largest should be the same type as each array element int largest = age[0]; for(index = 0; index < age_size; index++) { if (age[index] > largest) { largest = age[index]; } } |
Put an element into the beginning of an array// set element to be the thing to add for(index = lastnames_size; index > 0; index--) { lastnames[index] = lastnames[index-1]; } lastnames[0] = element; lastname_size++; |
Put an element into the end of an array// set element to be the thing to add lastnames[lastname_size] = element; lastname_size++; |
Printing an Array// The "15" spaces the array 15 pixels apart per element for(index = 0; index < age_size; index++) { g.drawString("" + age[index], 10, index * 15); } |
Printing an Array in Reverse// The "15" spaces the array 15 pixels apart per element for(index = score_size; index < 0; index++) { g.drawString("" + score[index], 10, (score_size - index) * 15); } |