Title: Arrays
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Arrays

Basics:

// Array big enough for 4 integers that are preset to 0
int[] arr = new int[4];

// Note that if you are a C++ programmer, Java will allow a similar
// syntax that is consistent with C++
int arr[] = new int[4]; // same effect as the previous statement

arr[0] = 1; // Setting first location
arr[3] = 3; // Setting last location
// arr[4] = 4 ; // This will halt your program with an exception

// You can have an array of anything:
String[] strArr= new String[5] ;
// Pretend that SomeClass has a constructor that
// takes a single integer parameter
SomeClass[] scArr= new SomeClass[6];

// Note that there is a big difference between using [] and () after the new operator:
String abc = new String("abc"); // Single instance of a String class
SomeClass sc = new SomeClass(123); Single instance of some class

// Note the default values of the following:
String str; // str will have a default value of null
String[] strArr = new String[3];
// strarr[0], strarr[1] and strarr[2] will have a values of null
// So to fully initialize, ...
strArr[0] = new String("abc");
strArr[1] = new String("xyz");
strArr[2] = new String("efg");

// If at some point you need to know how many entries are in an array,
// use the length property:
int len = strArr.length; // len should have a value of 3

Short Cuts to initializing:

int[] arr = {1, 2, 3};
// The above statement is exactly equivalent to:
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;

SomeClass[] scArr = {new SomeClass(987), new SomeClass(12), new SomeClass(78)};
// The above statement is exactly equivalent to:
SomeClass[] scArr = new SomeClass[3];
scArr[0] = new SomeClass(987);
scArr[1] = new SomeClass(12);
ScArr[2] = new SomeClass(78);

Special Short Cuts for the String class:

Because the String class is so important, there are special short cuts for the String class

The following 2 statements are equivalent:
String str = new String("abc");
String str = "abc";

Also the following 2 statements are equivalent for the String class:
String[] strArr = {new String("abc"), new String("xyz"), new String("efg")};
String[] strArr = {"abc", "xyz", "efg"};

Creating arrays



public class BasicArray
{
   //-----------------------------------------------------------------
   //  Creates an array, fills it with various integer values,
   //  modifies one value, then prints them out.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int LIMIT = 15, MULTIPLE = 10;

      int[] list = new int[LIMIT];

      //  Initialize the array values
      for (int index = 0; index < LIMIT; index++)
         list[index] = index * MULTIPLE;

      list[5] = 999;  // change one array value

      for (int i=0; i < list.length; i++)
        System.out.print(list[i] + "  ");

      System.out.println("");

      // The following loop does the exact same thing as the
      // previous loop.  This is a new feature recently added to the
      // Java language.

      for (int val : list)
         System.out.print (val + "  ");
   }
}






Accessing Arrays in Reverse Order


//********************************************************************
//  ReverseOrder.java
//
//  Demonstrates array index processing.
//********************************************************************

import java.util.Scanner;

public class ReverseOrder
{
   //-----------------------------------------------------------------
   //  Reads a list of numbers from the user, storing them in an
   //  array, then prints them in the opposite order.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Scanner scan = new Scanner (System.in);

      double[] numbers = new double[10];

      System.out.println ("The size of the array: " + numbers.length);

      for (int index = 0; index < numbers.length; index++)
      {
         System.out.print ("Enter number " + (index+1) + ": ");
         numbers[index] = scan.nextDouble();
      }

      System.out.println ("The numbers in reverse order:");

      for (int index = numbers.length-1; index >= 0; index--)
         System.out.print (numbers[index] + "  ");
   }
}



Initializing arrays


//********************************************************************
//  Primes.java
//
//  Demonstrates the use of an initializer list for an array.
//********************************************************************

public class Primes
{
   //-----------------------------------------------------------------
   //  Stores some prime numbers in an array and prints them.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};

      System.out.println ("Array length: " + primeNums.length);

      System.out.println ("The first few prime numbers are:");

      for (int prime : primeNums)
         System.out.print (prime + "  ");
   }
}



Command Line Arguments


//********************************************************************
//  NameTag.java
//
//  Demonstrates the use of command line arguments.
//********************************************************************

public class NameTag
{
   //-----------------------------------------------------------------
   //  Prints a simple name tag using a greeting and a name that is
   //  specified by the user.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      System.out.println ();
      System.out.println ("     " + args[0]);
      System.out.println ("My name is " + args[1]);
   }
}



Command Line Arguments: Print all arguments as strings


public class PrintStringArgs
{
   public static void main (String[] args)
   {
      for (int i=0; i < args.length; i++)
	       System.out.println(args[i]);
   }
}



Command Line Arguments: Print all arguments as integers

Note that you will get an Exception if any of the arguments are not integers


public class PrintIntArgs
{
   public static void main (String[] args)
   {
      for (int i=0; i < args.length; i++)
     {
           int val = Integer.parseInt(args[i]);
           System.out.println("val="+ val);
      }
   }
}



Command Line Arguments: Print all arguments as doubles

Note that you will get an Exception if any of the arguments are not doubles


public class PrintDoubleArgs
{
   public static void main (String[] args)
   {
      for (int i=0; i < args.length; i++)
     {
           double val = Double.parseDouble(args[i]);
           System.out.println("val="+ val);
      }
   }
}



Various Array Options


// This Example demonstrates different ways that arrays
// can be declared, uses, etc.


class ArrayTest{


// C/C++ syntax works to keep C++ people happy

static int  a1[] ;// Declares variable, but no memory allocation

public static void  main (String[] args) {
// ----------------------------------
// Completely Uninitialized arrays of ints:

    // Normal syntax
    int [] a2 =null; // Need to initialize to keep the compiler happy

    if (a1 == null) System.out.println("a1 is null now");
    if (a2 == null) System.out.println("a2 is null now");

    //  Uncomment out the following and you will get an error

    //    for (int i=0; i < a2.length; i++)
    //        System.out.println("a2(" + i + ") = " + a2[i]);

    a2 = new int[3];
    a2[0]=0;  a2[1]=1;  a2[2]=2;

    // Now this will work:

    for (int i=0; i < a2.length; i++)
         System.out.println("a2(" + i + ") = " + a2[i]);


// ----------------------------------
// Initialized Arrays ints
// a3 will have 4 array elements that are initialized to zeros
// a4 will have 4 array elements with the listed values

    int[] a3 = new int[4]; // memory allocation for 4 values initialized to zero
    int[] a4 = {1, 2, 3, 4, 5, 6}; // memory allocation + initialized values

    System.out.print("a3 contains: ");
    for (int i=0; i < a3.length; i++)
        System.out.print(a3[i] + ", ");

    System.out.println("");
    System.out.print("a4 contains:" );
    for (int i=0; i < a4.length; i++)
        System.out.print(a4[i] + ", ");

    System.out.println("");


    }//End of main



}// End of ArrayTest Class





Arrays of Classes:


class ArrayTest2{
public static void  main (String[] args) {
//-----------------------------------
// Arrays of Classes
// A5 will reference a 3 element array of null String references
// A6 will be a null reference

    String[] A5 = new String[3];
    String[] A6;  // A6 contains null now

// ----------------------------------
// A6 and A5 now point to the same Array reference
// originally owned by A5

    A6 = A5;


    // Create some Integer classes initialized with the specified values

    A6[0] = new String("aa");
    A6[1] = new String("bb");
    A6[2] = new String("cc");

    // Because A5 and A6 point to the same class reference, the following
    // will print out the class values we just created

    for (int  i= 0; i < A5.length; i++)
        System.out.println("A5(" + i + ") = " + A5[i]);

    }//End of main



}// End of ArrayTest2 Class





Strings Analysis using Arrays


//********************************************************************
//  LetterCount.java
//
//  Demonstrates the relationship between arrays and strings.
//********************************************************************

import java.util.Scanner;

public class LetterCount
{
   //-----------------------------------------------------------------
   //  Reads a sentence from the user and counts the number of
   //  uppercase and lowercase letters contained in it.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      final int NUMCHARS = 26;

      Scanner scan = new Scanner (System.in);

      int[] upper = new int[NUMCHARS];
      int[] lower = new int[NUMCHARS];

      char current;   // the current character being processed
      int other = 0;  // counter for non-alphabetics

      System.out.println ("Enter a sentence:");
      String line = scan.nextLine();

      //  Count the number of each letter occurence
      for (int ch = 0; ch < line.length(); ch++)
      {
         current = line.charAt(ch);
         if (current >= 'A' && current <= 'Z')
            upper[current-'A']++;
         else
            if (current >= 'a' && current <= 'z')
               lower[current-'a']++;
            else
               other++;
      }

      //  Print the results
      System.out.println ();
      for (int letter=0; letter < upper.length; letter++)
      {
         System.out.print ( (char) (letter + 'A') );
         System.out.print (": " + upper[letter]);
         System.out.print ("\t\t" + (char) (letter + 'a') );
         System.out.println (": " + lower[letter]);
      }

      System.out.println ();
      System.out.println ("Non-alphabetic characters: " + other);
   }
}



A new feature that was added to Java recently:


String[] strArr = {"abc", "xyz", "efg", "012", "789"};
for (int i=0; i < strArr.length; i++)
{
    String str = strArr[i];
	..... Rest of code accessing str
}

// The above loop is similar to:
for (String str : strArr)
{
   .... Rest of code accessing str
}


Another Example


//********************************************************************
//  GradeRange.java
//
//  Demonstrates the use of an array of objects.
//********************************************************************

public class GradeRange
{
   //-----------------------------------------------------------------
   //  Creates an array of Grade objects and prints them.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Grade[] grades =
      {
         new Grade("A", 95), new Grade("A-", 90),
         new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80),
         new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70),
         new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60),
         new Grade("F", 0)
      };

      for (Grade letterGrade : grades)
         System.out.println (letterGrade);
   }
}





//********************************************************************
//  Grade.java
//
//  Represents a school grade.
//********************************************************************

public class Grade
{
   private String name;
   private int lowerBound;

   //-----------------------------------------------------------------
   //  Constructor: Sets up this Grade object with the specified
   //  grade name and numeric lower bound.
   //-----------------------------------------------------------------
   public Grade (String grade, int cutoff)
   {
      name = grade;
      lowerBound = cutoff;
   }

   //-----------------------------------------------------------------
   //  Returns a string representation of this grade.
   //-----------------------------------------------------------------
   public String toString()
   {
      return name + "\t" + lowerBound;
   }


}





Various 2-Dimensional Array Options




class ArrayTest{



public static void  main (String[] args) {

// a7 is a 2 dimensional array filled with zeros
// a8 is a 2 dimensional array with 2 rows and 3 columns and
//           the elements contain the specified values
    int [][]a7 = new int [2][3];
    int [][]a8 = {
            {1,2,3},
            {4,5,6}
             };


    for (int i= 0; i < a8.length; i++)
        for (int j = 0; j < a8[i].length; j++)
           System.out.println("a8(" + i + "," + j + ") = " + a8[i][j]);

    }//End of main



}// End of ArrayTest Class



Two Dimensional Array


//********************************************************************
//  TwoDArray.java       Author: Lewis/Loftus
//
//  Demonstrates the use of a two-dimensional array.
//********************************************************************

public class TwoDArray
{
   //-----------------------------------------------------------------
   //  Creates a 2D array of integers, fills it with increasing
   //  integer values, then prints them out.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int[][] table = new int[5][10];

      // Load the table with values
      for (int row=0; row < table.length; row++)
         for (int col=0; col < table[row].length; col++)
            table[row][col] = row * 10 + col;

      // Print the table
      for (int row=0; row < table.length; row++)
      {
         for (int col=0; col < table[row].length; col++)
            System.out.print (table[row][col] + "\t");
         System.out.println();
      }
   }
}



Another 2 Dimensional Array


//********************************************************************
//  SodaSurvey.java       Author: Lewis/Loftus
//
//  Demonstrates the use of a two-dimensional array.
//********************************************************************

import java.text.DecimalFormat;

public class SodaSurvey
{
   //-----------------------------------------------------------------
   //  Determines and prints the average of each row (soda) and each
   //  column (respondent) of the survey scores.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      int[][] scores = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4},
                         {2, 4, 3, 4, 3, 3, 2, 1, 2, 2},
                         {3, 5, 4, 5, 5, 3, 2, 5, 5, 5},
                         {1, 1, 1, 3, 1, 2, 1, 3, 2, 4} };

      final int SODAS = scores.length;
      final int PEOPLE = scores[0].length;

      int[] sodaSum = new int[SODAS];
      int[] personSum = new int[PEOPLE];

      for (int soda=0; soda < SODAS; soda++)
         for (int person=0; person < PEOPLE; person++)
         {
            sodaSum[soda] += scores[soda][person];
            personSum[person] += scores[soda][person];
         }

      DecimalFormat fmt = new DecimalFormat ("0.#");
      System.out.println ("Averages:\n");

      for (int soda=0; soda < SODAS; soda++)
         System.out.println ("Soda #" + (soda+1) + ": " +
                    fmt.format ((float)sodaSum[soda]/PEOPLE));

      System.out.println ();
      for (int person =0; person < PEOPLE; person++)
         System.out.println ("Person #" + (person+1) + ": " +
                    fmt.format ((float)personSum[person]/SODAS));
   }
}



Exercises:

1. Which of the following are valid declarations? Which instantiate an array object? Explain your answers.
int primes = {2, 3, 4, 5, 7, 11};
float elapsedTimes[] = {11.47, 12.04, 11.72, 13.88};
int[] scores = int[30];
int[] primes = new {2, 3, 5, 7, 11};
int[] scores = new int[30];
char grades[] = {'a', 'b', 'c', 'd', 'f'};
char[] grades = new char[];
2. Describe what problem occurs in the following code. What modifications should be made to it to eliminate the problem?
int [] numbers = {3,2,3,6,9,10,12,32,3,12,6};
for (int count = 1; count <= numbers.length; count++)
System.out.println (numbers[count]);
3. Java passes parameters with one of 2 approaches:
  - Call by value ( a copy is passed to the calling routine) - the caller's data can NOT be modified
  - Call by reference(a handle to the object is passed) - the caller's data can be modified
See if you can figure out which method is used for the following types of data (int, double, boolean, array of ints, Strings, regular classes)
4. Write code that prints the values stored in an array called names backwards.
5. Write code that sets each element of a boolean array called flags to alternating values (true at index 0, valse at index 1, true at index 2, etc.);
6. Write a method called sumArray that accepts an array of floating point values and returns the sum of the values stored in the array.
7. Write a method called switchThem that accepts two integer arrays as parameters and switches the contents of the arrays. Take into account that arrays may be of different sizes.
8. Design and implement an application that creates an array of random integers that are in the range 0 to 50 inclusive. The size of the array can be a parameter to your program. Your application then outputs a count of how many occurences of each number in the random array.
9. Modify the previous example so that it works for numbers in the range between -25 and 25.
10. Design and implement an application that creates a histogram that allows you to visually inspect the frequency distribution of a set of values. The program should read in an arbitrary number of integers that are in the range 1 to 100 inclusive; then produce a chart similar to the one below that indicates how many input values fell in the range 1 to 10, 11 to 20, and so on. Print one asterisk for each value entered.


	-----------------------------------------
	| 1 - 10 | *****                        |
	|11 - 20 | **                           |
	|21 - 30 | ******************           |
	|31 - 40 |                              |
	|41 - 50 | ***********                  |
	|51 - 60 | **                           |
	|61 - 70 | *******                      |
	|71 - 80 | *****                        |
	|81 - 90 | ************                 |
	|91 -100 | ************************     |
	-----------------------------------------
	
	

11. Modify the above program so that it can handle large numbers by scaling the number of asterisks. Choose a scaling factor such that an asterisk represents N values. In otherwords, the number of asterisks will be the number of values/N.
12. Create a program that computes the average and the standard deviation of an array of doubles. Test it with an array of random numbers.
Standard Deviation = SQRT( sum(x_i - average)^2/(N -1) )
13. Create a Black Jack game, where you play against the computer. Steps to this:
  - Create a Card Class
  - Create a Black Jack class that contains an array of 52 cards called the Deck
  - Create a routine that does a shuffle of the cards : hint for each card in the deck call the random number generater to get a random card location to swap with this card.
  - Create a method to take a new card. Note that this can get tricky when the deck is almost exhausted in the middle of a hand. You might want to simplify by having a parameter that indicates this is the beginning of a new round and we should consider starting with a new shuffled deck.
  - Create appropriate routines to play the game.
14. Create a Tic-Tac-Toe game.

Last Modified: February 18, 2008 1:28 PM