title slid csc 444 java programming arrays by ralph b. bisland, jr

30
Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr.

Upload: osborn-richard

Post on 18-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

Title Slid

CSC 444

Java Programming Arrays By

Ralph B. Bisland, Jr.

Page 2: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

2

Arrays• An array is a object of a class.

• To declare an array, specify the data type followed by square brackets, followed by the name of the array.

• Example:int [] numbers;• Creates only one memory location for numbers

and its contents is null.

• To allocate space for the array, we must instantiate the class with the word “new”.

Page 3: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

3

Arrays (ctd)• Syntax to declare a one dimensional array

type [] identifier = new type[number of cells];

• Example:int [] numbers = new int [5];

• The array is called “numbers” and it has 5 integer cells.

• The cell subscripts are 0..4.

Page 4: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

4

Storing Values Into An Array• Two methods of storing values into an

array

–By initialization at the point of declaration

–By assigning the numbers to cells directly

Page 5: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

5

Initialization• Syntax:

type [] identifier = [list of values];

• Example:int[] numbers = {10, 20, 30};

• The compiler automatically sets the length of the array to 3.

• Conceptually:

numbers indexes 0 1 2

10 20 30

Page 6: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

6

Assigning Values In Directly• To assign values in directly, use the

indexes to indicate what position to insert the new value into.

• Example:int[] numbers = new int [5];numbers [0] = 1;numbers [2] = 10;numbers [4] = 5*4;

Page 7: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

7

Array Exceptions• Java always checks array indexes for

legal values.

• If an illegal value is produced, the following exception is thrown.

ArrayIndexOutOfBoundsException

Page 8: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

8

Dynamic Arrays• Array size can be declared at execution

time.

• Exampleint sizeOfArray;sizeOfArray =

SimpleInput.readInt();int[] numbers = new int [sizeOfArray];

Page 9: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

9

Example Problem

• Write a Java program to determine if a word is a palindrome.

• Method to convert a string to an array of characters: toCharArray().

• Method to convert a string to all uppercase characters: toUpperCase().

• Variable that determines the number of cells in an array: length. Note: There is a method called length() that returns the current length of a string.

Page 10: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

10

Java Solution

// Palindrome Problemimport java.io.*;Import SimpleIO.*;class Palindrome{ static public void main (String[] args) throws IOException { String word; int left, right; boolean charactersMatch;

Page 11: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

11

Java Solution (ctd)do

{ charactersMatch = true; System.out.print(“Input a word “); word = SimpleInput.readString(); char[] characterArray = word.toUpperCase().toCharArray(); left = 0; right = characterArray.length-1; while (left <= right && charactersMatch) { if (characterArray[left] == characterArray [right]) {left++; right--;} else charactersMatch = false; }

Page 12: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

12

Java Solution (ctd)if (charactersMatch)

System.out.println (word + “ is a palindrome\n”); else System.out.println (word + “is not a palindrome\n”);} while (charactersMatch)’}}

Page 13: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

13

Arrays Of Objects• Java allows arrays of objects (ex. Arrays of Strings).

• Examples: String[] names;names = new String[4];

names [0] = “Cartman”;names [1] = “Kenny”; names [2] =

“Kyle”; names [3] = “Patrick”;String [] names = {“Cartman”,

“Kenny”, “Kyle”, “Patrick”};

Page 14: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

14

Multidimension Arrays• Java arrays can be N dimensional.

• Declaration of multidimensional arraysint [][] myArray = new int [3] [4];myArray[0][0] = 1;myArray[0][1] = 2;

int [][] myArray = {{1, 2, 3, 4},{5,6,7,8},{9, 10, 11, 12}};

Page 15: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

15

Vectors• Unless reinstantiated, array dimensions are

fixed.• An object Vector allows “unlimited” storage.• The class Vector is part of the package java.util.

• When a vector can not store any more data, the vector automatically doubles its size (provided enough storage is available).

Page 16: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

16

Partial Listing Of The Class Vectorpublic class Vector extends Object

implements Clonable{ // Constructors public Vector (int initialCapacity); // Methods public final void addElement (Object obj); public final int capacity(); public final Object elementAt (int Index); public Object firstElement(); public final int indexOf (Object elem); public Object lastElement() public final int size(); public final void trimToSize();}

Page 17: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

17

What Vector Components DoinitialCapacity: Specified the initial capacacity of Vector.

addElement: Inserts an object into the next free location.capacity: Returns the capacity of the Vector.elementAt: Returns the Object stored at position index.firstElement: Returns the Object at position zero.indexOf: Returns the index of the object stored in the Vector.lastElement: Returns the object element stored in the position size-1.size: Returns the number of object elements stored in the Vector.trimToSize: Reduces the capacity of the Vector to the number of elements stored in the Vector.

Page 18: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

18

Example Program With Vectorsimport java.io.*;

import java.util.*;Import SimpleIO.*;class Test_Vector{ public static void main(String[] args) throws IOException { final int INITIAL_SIZE = 4; Vector dataStore = new Vector(INITIAL_SIZE); int sizeOfVector; String word; System.out.println (“Input single words, one per line” + “, enter QUIT to quit\n”); System.out.print (“Word: “); word = SimpleInput.readString();

Page 19: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

19

Program (ctd)while (! word.equals.(”QUIT”))

{ dataStore.addElement(word); System.out.println (“index “+dataStore.indexOf(word) + “\tcontents “+word + “\tcapacity of vector “ + dataStore.capacity()); System.out.print (“Word: “); word = SimpleInput.readString(); }System.out.println(“\nsize of vector: “ + dataStore.size;

Page 20: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

20

Program (ctd)System.out.println (“capacity of vector: “ +

dataStore.capacity();System.out.println (“first element of vector: “ + dataStore.firstElement();System.out.println (“last element of vector: “ + dataStore.lastElement();System.out.println (“element at index 5: “ + dataStore.element(5);dataStore.trimToSize();sizeOfVector = dataStore.capacity();System.out.println (“\ntrimmed size capacity: “ + sizeOfVector);System.out.println (“Contents Of Vector\n”);for (int index=0;index!=sizeOfVector;index++) {System.out.println (dataStore.elementAt(index) + “ “);} } }

Page 21: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

21

Non-Rectangular Arrays• Multidimensional arrays are arrays of arrays.

• Multidimensional arrays do not have to be rectangular.

• Example:int[][] twoD = {{1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}};

• Array: 12 3 4 5 67 8 9 10

Page 22: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

22

Non-Rectangular Array Programimport java.io.*;

class Nra{ public static void main (String[] args) throws IOException { final int MAX_CELLS = 4; int[][] twoD = {{1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}}; int cells = 1; for (int row=0; row!=cells; row++) {for int col=0; col!=cells; col++) {System.out.print(twoD[row][col]+”\t”);} scr.println();

Page 23: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

23

Program (ctd) if (cells < MAX_CELLS)

cells++; else break; } System.out.println(); }}

Page 24: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

24

Passing Arrays to Methods• Arrays are passed as reference

parameters to methods.

• Since arrays are passed as reference parameters their cell values can be modified in the method.

• Arrays are mutable in methods.

Page 25: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

25

AddArrays.javaclass AddArrays

{ public static void main (String [] args) { int[] array1 = {1, 3, 5, 7, 9}; int[] array2 = {2, 4, 6, 8}; System.out.println (“Array 1 sum: “ + sum (array1); System.out.println (“Array 2 sum: “ + sum (array2); } public static int sum (int[] x) { int sum = 0; for (int i = 0; I < length.x; i++) sum = sum + x [i]; return sum; } }

Page 26: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

26

CopyArrays.javaClass CopyArrays

{ public static void main (String [] args) { int[] Array1 = {1, 2, 3, 4}; int[] Array2 = {5, 6, 7, 8}; copy (Array1, Array2); for {int i=0; i< Array1.length; i++) System.out.print (array1[i] + “ “); system.out.flush(); for {int i=0; i< Array2.length; i++) System.out.print (array2[i] + “ “); system.out.flush();} public static void copy (int[] x, int[] y) {for (int i=0;i<x.length;i++) y[i]=x[i];} }

Page 27: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

27

Reading Values From The Command Line• The parameter list in the main method

allows users to read values from the command line when executing the program.

• String [] args allows us to access String values from the command line.

• args[0] is the first value, args[1] is the second, etc.

• args.length tells us how many values were entered.

Page 28: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

28

Values From The Command Line• All values are “read in” as strings.

• If a values needs to be any primative type it can be converted with the Wrapper classes or the parseType methods.– Integer.parseInt()– Long.parseLong()– Float.parseFloat()– Double.parseDouble()– Boolean.parseBoolean()

Page 29: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

29

Values From The Command Line (ctd)• The values to be input are placed on the

“java” command line after the program name.

$ java Program Value1 Value 2• If you are using an IDE to run your Java

programs there will be some type window where your enter these values. This window is different for each IDE.

Page 30: Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr

30

ReadIn.javaclass ReadIn

{public static void main (String[] args) { String firstName = args[0]; String lastName = args[1]; int IQ = Integer.parseInt(args[2}); System.out.println(“First Name: “ + firstName); System.out.println (“Last Name: “ + lastName);; System.out.println (“IQ: “ + IQ); } }$javac ReadIn.java$java ReadIn Ralph Bisland 53