1 / 30

Title Slid

Title Slid. CSC 444. Java Programming Arrays By Ralph B. Bisland, Jr. 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;

akimberly
Download Presentation

Title Slid

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

  3. 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. Arrays (ctd)

  4. Two methods of storing values into an array By initialization at the point of declaration By assigning the numbers to cells directly Storing Values Into An Array

  5. Syntax: type [] identifier = [list of values]; Example: int[] numbers = {10, 20, 30}; The compiler automatically sets the length of the array to 3. Conceptually: Initialization 10 20 30 numbers indexes 0 1 2

  6. 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; Assigning Values In Directly

  7. Java always checks array indexes for legal values. If an illegal value is produced, the following exception is thrown. ArrayIndexOutOfBoundsException Array Exceptions

  8. Array size can be declared at execution time. Example int sizeOfArray; sizeOfArray = SimpleInput.readInt(); int[] numbers = new int [sizeOfArray]; Dynamic Arrays

  9. 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. Example Problem

  10. Java Solution // Palindrome Problem import 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. 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”}; Arrays Of Objects

  14. Java arrays can be N dimensional. Declaration of multidimensional arrays int [][] 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}}; Multidimension Arrays

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

  16. Partial Listing Of The Class Vector public 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 Do initialCapacity: 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 Vectors import 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. 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: 1 2 3 4 5 6 7 8 9 10 Non-Rectangular Arrays

  22. Non-Rectangular Array Program import 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. 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. Passing Arrays to Methods

  25. AddArrays.java class 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.java Class 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. 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. Reading Values From The Command Line

  28. 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() Values From The Command Line

  29. 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. Values From The Command Line (ctd)

  30. ReadIn.java class 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

More Related