University of Toronto - Fall 2000
Department of Computer Science

Week 10 - Working with Arrays

Working with Arrays (of primitive type and of class type)


Arrays of primitive type

import java.io.*;

// ManagePrimArray:  This class manages a list of integers.  It reads in
//   the values from input, stores them in an array, and then prints
//   the contents of the array on a single line of output.
public class ManagePrimArray {

	public static void main (String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader
				(System.in));

		// Read the size of the list, 'N'.
		System.out.print ("Number of values? ");
		int N = Integer.parseInt(in.readLine());
	
		// Declare and instantiate an array 'a' to hold 'N' integers.
		int[] a = new int[N];
	
		// Read contents of 'a' from input.
		for (int i = 0; i < N; i++) {
			System.out.print ("Enter a value: ");
			a[i] = Integer.parseInt(in.readLine());
		}

		// Print contents of 'a' on a single line of output.
		System.out.println ("\nHere are the values in the array:");
		for (int i = 0; i < N; i++) {
			System.out.print (a[i] + " ");
		}
		System.out.println();
	}
}

Output for ManagePrimArray.java

Number of values? 5
Enter a value: 2
Enter a value: 9
Enter a value: 1
Enter a value: 2
Enter a value: 3

Here are the values in the array:
2 9 1 2 3

Arrays of class type

import java.io.*;

// ManageClassArray:  This class manages a list of Student objects.  It
//   reads in name and student number for each student and uses this to
//   construct a Student object which is stored in the array.  It then
//   prints the name of each student in the array.
public class ManageClassArray {

	public static void main (String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader
				(System.in));

		// Read the size of the list, 'classSize'.
		System.out.print ("Number of students? ");
		int classSize = Integer.parseInt(in.readLine());

		// Declare and instantiate an array 'section' to hold 'classSize'
		// Student objects.
		Student[] section = new Student[classSize];

		// Read in name and id for each student, and use this to
		// construct Student objects which are placed in
		// the 'section' array.
		for (int i = 0; i < section.length; i++) {
			System.out.print ("Student name? ");
			String name = in.readLine();
			System.out.print ("Student ID? ");
			String id = in.readLine();

  			section[i] = new Student (name, id);
		}

		// Print names of each student
		System.out.println ("\nHere are the student names:");
		for (int i = 0; i < section.length; i++) {
			System.out.println (section[i].getName());
		}
	}
}

Output for ManageClassArray.java

5
Clarke  Jim
980999392
Hunter  Andria
993456655
Smith  Jane
888333444
Ginger  Ryan
990222334
Henry  John
998000992

Here are the student names:
Clarke  Jim
Hunter  Andria
Smith  Jane
Ginger  Ryan
Henry  John