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

Post on 18-Jan-2016

219 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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”.

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.

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

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

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;

7

Array Exceptions• Java always checks array indexes for

legal values.

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

ArrayIndexOutOfBoundsException

8

Dynamic Arrays• Array size can be declared at execution

time.

• Exampleint sizeOfArray;sizeOfArray =

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

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.

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;

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; }

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)’}}

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”};

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}};

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).

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();}

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.

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();

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;

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) + “ “);} } }

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

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();

23

Program (ctd) if (cells < MAX_CELLS)

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

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.

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; } }

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];} }

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.

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()

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.

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

top related