CT 229 Arrays Continued 20/10/2006 CT229
Lab Assignments Current lab assignment is due today: Oct 20 th Before submission make sure that the name of each.java file matches the name given in the assignment sheet!!!! Remember: Electronic Submission @ http://ecrg-vlab01.it.nuigalway.ie/uploader/submissions.html New Lab Assignment Currently Available on Website Due Date Friday 3 rd of November 20/10/2006 CT229 1
Lab Assignments Results of Lab Assignment 2 are up on the website http://www.nuigalway.ie/staff/ted_scully/ct229/labs.html Marks were mainly lost due to lack of formatting 20/10/2006 CT229 2
Formatting Naming Conventions Do not use single letters as variable names (use words) Variable names should start with a lower-case letter (accountbalance) Constants should have all upper-case letters (INTEREST_RATE) Naming convention for methods should be same as for variables (getbankbalance) 20/10/2006 CT229 3
Formatting-Comments Header Comment /* Simple Java program that prints a Hello message */ /* John Doe, Student Number: 00003112 */ Single Line Comment // Get hourly pay rate in string form: convert to double ratestr = JOptionPane.showInputDialog("Enter Hourly Rate:"); rate = Double.parseDouble(rateStr); 20/10/2006 CT229 4
Formatting Indentation and Space Use of indentation and space makes code easier to read Simple Rules for indentation After each move the subsequent code in by three spaces Open and close parentheses should be inline with each other /* Simple Java program that prints a Hello message */ /* Ted Scully, Sept 2006 */ public class Hello public static void main(string[] args) System.out.println("Hello World!"); 20/10/2006 CT229 5
Review of Last Week- Overloading Method Overloading: Java allows different methods of the same name to be defined, as long as they have different parameter lists The signature of each method must be unique Method Signature: Name of method + data types of parameters, in given order: Basic principle: The compiler must be able to determine unambiguously which version of method to call 20/10/2006 CT229 6
Review of Last Week public static void printmethod(int num) System.out.println("You entered an int with value "+num); public static void printmethod(double num) System.out.println("You entered an double with value "+num); public static void printmethod(boolean condition) System.out.println("You entered a boolean with value "+condition); 20/10/2006 CT229 7
Review of Last Week- Recursion Recursion occurs when a methods calls itself either directly or indirectly. A recursive method must have: 1. Test to stop or continue the recursion 2. A base case that terminates the recursion 3. Recursive call(s) that continue the recursion 20/10/2006 CT229 8
Recursive Summation public static void main(string[] args) int num = 4; int total = summation(num); System.out.println("Total is "+total); public static int summation(int num) if (num == 1) else return 1; return ( num + summation(num-1) ); 20/10/2006 CT229 9
Recursion Fibonacci Example => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233. 20/10/2006 CT229 10
Recursion Fibonacci Example public static int fibonacci(int n) if (n == 0) return 0; else if (n == 1) else return 1; return fibonacci(n-1) + fibonacci(n-2); 20/10/2006 CT229 11
CT 229 Arrays in Java 20/10/2006 CT229
Arrays in Java An array is a collection of variables all of the same data type/class single array name to refer to all elements subscript/index to identify individual (starting at 0) square brackets [] used to denote array index Array has fixed length specified when allocating memory; cannot be re-sized later, will see more flexible & advanced collection classes Declaring and allocating an array: int[] intarray = new int[12]; Placement of brackets in declaration: Either int[] c, d, e; // preferred Or int c[], d[], e[]; // C-style 20/10/2006 CT229 13
Array Example int[] g; // declare g = new int[8]; // allocate memory g[0] = 20; g[1]=0; // initialise vals g[2] = 30; g[3]=12; g[4] = 13; g[5]=38; g[6] = 3; g[7]=55; g refers to whole array; g[0] refers to int at first position 20 0 30 12 13 38 3 55 g[0] g[1] g[2] g[3] g[4] g[5] g[6] g[7] 20/10/2006 CT229 14
Initialiser List, Indexing, Length Can specify initialiser list: double[] n = 1.01, 2.22, 30.3, 4.444, 55.0 ; new not needed here: attaching array reference to array object that is automatically created and values set Size and index can be variables or expressions Must evaluate to an integer value int size =... ; // ask user double[] x = new double[size]; double last = x[size 1]; Size can be found with arrayname.length for (int i=0; i < n.length; i++) System.out.println("Item " + i + " is " + n[i] ); 20/10/2006 CT229 15
Passing Array To Methods Passing individual array elements Pass subscripted name (e.g. arr[3]) to method No different to a standard (non-array) variable Passing arrays Specify array name without brackets int arr[24]; dosomething(arr); Arrays are passed by reference: if changed in method, modifies original memory Definition of method dosomething: void dosomething(int[] a)... Don't specify size: array knows its own length (unlike C) 20/10/2006 CT229 16
Passing Array Value to a Method // Array Elements passed to a method by value just like primitive types such as int, double etc. public static void main(string[] args) int[] intarray = 34, 35, 36; System.out.println(intArray[0]); alterarray(intarray[0]); System.out.println(intArray[0]); 34 34 public static void alterarray(int arraynum) arraynum = 123; 20/10/2006 CT229 17
Passing Arrays To Methods Example // ARRAYS ARE PASSED BY REFERENCE UNLIKE PRIMITIVE TYPES public static void main(string[] args) int[] intarray = 34, 35, 36; System.out.println(intArray[0]); 34 123 alterarray(intarray); System.out.println(intArray[0]); public static void alterarray(int[] array) array[0] = 123; 20/10/2006 CT229 18
Returning Arrays From Methods Similar to passing array to method: In method declaration, start with datatype[] with to indicate that an array is being returned In return statement, use bare array name without [] to refer to entire array 20/10/2006 CT229 19
Returning Arrays From Methods public static void main(string[] args) String[] stringarray = definearray(); System.out.println(stringArray[0]+stringArray[1]); private static String[] definearray() Hello World String[] array = new String[2]; array[0] = "Hello "; array[1] = "World"; return array; 20/10/2006 CT229 20
Multi-Dimensional Arrays As well as rows (1D), can have tables (2D) and higherdimensional arrays Basically arrays of arrays (of arrays ) Use additional sets of [] To declare 2D array of ints, size 3x4: int[][] a = new int[3][4]; Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[0][0] a[1][0] a[2][0] a[0][1] a[1][1] a[2][1] a[0][2] a[1][2] a[2][2] a[0][3] a[1][3] a[2][3] Array name Column subscript Row subscript 20/10/2006 CT229 21
Multi-Dimensional Arrays int[][] numarray = new int[4][2]; 0 0 0 0 0 0 0 0 Can use nested initialiser lists: int[][] b = 1,2,3,4,5,6; 1 3 5 2 4 6 20/10/2006 CT229 22
Multi-Dimensional Arrays Can pull apart 2D array into several 1D arrays: int[][] b = 1,2,3,4,5,6; int[] x = b[2]; x[0] = 5 x[1] = 6 for (n=0; n<2; n++) System.out.println("x[" + n + "] = " + x[n]); b.length => number of rows (first dimension) b[0].length=> number of cols (second dimension) Example: Array2D.java 20/10/2006 CT229 23
Multi-Dimensional Arrays int[][] b = 1,2,3,4,5,6; int[] x = b[2]; System.out.println("Before ---> "+x[0]); System.out.println("After ---> "+b[2][0]); x[0] = 23443; System.out.println("Before ---> "+x[0]); System.out.println("After ---> "+b[2][0]); Before ---> 5 After ---> 5 Before ---> 23443 After ---> 23443 Example: Array2D.java 20/10/2006 CT229 24
Muli-Dimensional Arrays Can have ragged arrays: Array where rows have different number of columns int[][] ragged = new int[3][]; // 3 rows; //unknown cols ragged[0] = new int[2]; // first row: 3 cols ragged[1] = new int[4]; ragged[2] = new int[3]; Example: ArrayRag.java 20/10/2006 CT229 25
Arrays and Command Line Arguments Popular technique for giving input to programs Supported by most programming languages In Java programs: When running program, any text typed after program name is split on spaces and put in a String array, args This is passed by JVM as parameter to main method Program can inspect args to determine what was typed Example: SayHello.java Program that says hello, given name in input Usage: java SayHello Ted Scully 20/10/2006 CT229 26
SayHello.java public class SayHello public static void main(string[] args) if (args.length == 1) System.out.println("Hello there, " + args[0] + "."); else if (args.length == 2) System.out.println("Hello " + args[0] +" "+ args[1]); else System.out.println("Usage: java SayHello <name>"); 20/10/2006 CT229 27