Chapter 6: Arrays


Chapter 6: Arrays and ArrayLists

Highlights review:

  • In Java, arrays are objects
  • Arrays can be create with the “new” operator: int[] height = new int[11]
  • Arrays can also be created in using this format: int[] scores = {76, 87, 99}
  • The index operator [ ] performs automatic bounds checking
  • Beware of the off-by-one errors in a program
  • Either syntax int[] grades or int grades[] is correct

NOTE: The following programs and the pdf are stored in edmodo’s folder. Get familiar with all these programs and their algorithms to further develop assignments.

BasicArray

//********************************************************************
//  BasicArray.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates basic array declaration and use.
//********************************************************************

public class BasicArray
{
   final static int LIMIT = 15;
   final static int MULTIPLE = 10;
                   
   //-----------------------------------------------------------------
   //  Creates an array, fills it with various integer values,
   //  modifies one value, then prints them out.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      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 index = 0; index < LIMIT; index++)
         System.out.print (list[index] + "  ");
      
      System.out.println ();
   }
}

[collapse]
Primes

//********************************************************************
//  Primes.java       Author: Lewis/Loftus/Cocking
//
//  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 scan = 0; scan < primeNums.length; scan++)
         System.out.print (primeNums[scan] + "  ");

      System.out.println ();
   }
}

[collapse]

Printing an array of integers in reverse order:

ReverseOrder

//********************************************************************
//  ReverseOrder.java       Author: Lewis/Loftus/Cocking
//
//  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)
   {
      double[] numbers = new double[10];
      Scanner scan = new Scanner(System.in);

      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] + "  ");
      
      System.out.println ();
   }
}


Output:
The size of the array: 10
Enter number 1: 18.36
Enter number 2: 48.9
Enter number 3: 53.3
Enter number 4: 21.9
Enter number 5: 34.7
Enter number 6: 12.5
Enter number 7: 78.4
Enter number 8: 98.1
Enter number 9: 99.0
Enter number 10: 37.9
The numbers in reverse order:
37.9 99.0 98.1 78.4 12.5 34.7 21.9 53.3 48.9 18.36

[collapse]

Letter counting

LetterCount

//********************************************************************
//  LetterCount.java       Author: Lewis/Loftus/Cocking
//
//  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);
   }
}

Output:
Enter a sentence:
In Casablanca, Humprey Bogart never says "Play it again, Sam."


A: 0		a: 10
B: 1		b: 1
C: 1		c: 1
D: 0		d: 0
E: 0		e: 3
F: 0		f: 0
G: 0		g: 2
H: 1		h: 0
I: 1		i: 2
J: 0		j: 0
K: 0		k: 0
L: 0		l: 2
M: 0		m: 2
N: 0		n: 4
O: 0		o: 1
P: 1		p: 1
Q: 0		q: 0
R: 0		r: 3
S: 1		s: 3
T: 0		t: 2
U: 0		u: 1
V: 0		v: 1
W: 0		w: 0
X: 0		x: 0
Y: 0		y: 3
Z: 0		z: 0

[collapse]

Non-alphabetic characters: 14

Array length: 8
The first few prime numbers are:
2  3  5  7  11  13  17  19  

Helpful notes for testing purposes:
Instead of entering manually input, you could put the data in a file like input.data. Take a look at an easy way to read data from a file:

import java.util.Scanner;
public class ScannerInTerminal
{
    public static void main(String [] args)
    {
        Scanner sc = new Scanner(System.in);
        String fromTerm = sc.next();
        System.out.println(fromTerm);
    }
}

Then you can run it in Terminal
mrseliaTerminal%: java ScannerInTerminal < input.txt 3.14159…
Classwork:

Programming Projects 6.1, 6.2, 6.4 and 6.5


Homework:

Short Answers 6.1, 6.2 and 6.3
Read pages 298 through 311