Creating an Array

From CompSciWiki
Revision as of 15:41, 4 December 2011 by JordanW (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

There are ten students with ten grades. Instead of storing every single grade in a single variable it is easier to store this information in an array. The grades of the ten students are 56%, 34%, 75%, 89%, 78%, 87%, 71%, 67%, 98%, 85%. Do the following:

  1. Store the grades in an integer array as percents.
  2. Convert them to decimals and store them in a double array.
  3. Store the names of each student in a String array.
 

Introducing Array

Wiki array01.jpg

Solution

First create the skeleton structure of your program

 public class CreatingArray{
  public static void main(){
  }
} 

Next, the two arrays to be used are integer and double, so we need to create the variables that will store these arrays.

 int[] intArray;
double[] decimalArray;
String[] stringArray; 

These will go inside the main program. Now a new array must be created, this is done with the new keyword.

 intArray = new int[10];
decimalArray = new double[10];
stringArray = new String[10]; 

The 10 specifies the size of the array that you want to create. Now we will need to store the values inside the array. This is done by equating each position within the array with they value we want to store.

 intArray[0] = 56;
decimalArray[0] = intArray[0]/100.0; // or decimalArray[0] = 0.56;
stringArray[0] = "Bill";
intArray[1] = 34;
decimalArray[1] = 0.34;
stringArray[1] = "Bob";
etc. 

If the numbers that you are entering are known before hand, as in this case, it's much faster to create the array in short hand format. This is done by creating your array variable and immediately assigning a list of values to it. This will automatically create the new array of the required size and initialize elements in the array to the appropriate value. This short hand for the first 3 numbers or strings will look like this:

 int[] intArray;
intArray = {56, 34, 75};
String[] stringArray;
stringArray = {"Bill", "Bob", "Betty"}; 

This can also be done in one line.

 int[] intArray = {56, 34, 75};
String[] stringArray = {"Bill", "Bob", "Betty"}; 

All that needs to be done now is to create the three arrays for the grades.

Code

Solution Code

Back to the Program-A-Day homepage