HC Computing craig.ian@itsligo.ie Java – Arrays, Functions and Exception Handling Data Arrays Continuing on the data theme, we can group the basic data types (integers, floats, chars or even strings) into arrays, which we can process via a loop or an index. Arrays use the [] symbols are declared (defined) and initialized as follows: int[] smallPrimes = { 2,3,5,7,11,13,17,19 }; String[] greetings = {“hi”, “how’s it going”, “hello”}; You can reference an entry in the array by specifying an index in the brackets. Greetings[0] = ‘hi’ or smallPrimes[5] = 11 You can use built in Java functions in java.util.Arrays to get values like the length of an array of the number of elements in an array. For example: class Arrays { public static void main(String args[]) { int[] primes = new int[] {2,3, 5, 7, 11, 13, 17, 19 }; String[] textPrime = new String[] {"two", "three", "five", "seven", "eleven", "thirteen", "seventeen", "nineteen"}; // Print the arrays // System.out.println ("Small primes and their English text"); } } for(int i=0; i<(primes.length); i++) { System.out.println (textPrime[i] + ": " + primes[i]); } // end main This is a sample program which will print out the arrays in a list. Lab 1 for this week will use the basis of this program for running our lab on BlueJ Page 1 of 5 HC Computing craig.ian@itsligo.ie Java – Arrays, Functions and Exception Handling Inputing data. Up to now, we have only output data, using the println instruction. You can ask for data by specifying the built in scanner function from Java. /* The scanner is used for input. This is part of the accompanying Java library. You need to import any library functions you use. See the Java in a Nutshell book or any Java documentation for a list of library functions. */ import java.util.Scanner; class keyboardInput{ public static void main(String args[]) { Scanner keyboard; String name; // we define the type here // needed for name keyboard = new Scanner (System.in); // take input from the keyboard // 1. ask for something System.out.println (“What’s your name?"); name = keyboard.nextLine(); // get input // display it System.out.println("Well Hi there " + name + ", how are you doing?"); } } Enter this program and run it from the command line. The program should be called keyboardInput.java Compile it with javac And run with java Page 2 of 5 HC Computing craig.ian@itsligo.ie Java – Arrays, Functions and Exception Handling Notes on calling and writing methods Methods or functions are simply pieces of Java code which do a specific task. We are used to them at this stage. For example the method add will take in two float numbers and add them together, returning the result. static float add (float a, float b) { // do the work return (a + b); } Is a simple function which takes in two inputs and returns one output of type float. Some functions or methods do not need to return anything and should be declared as void. static void printAll (int index) { int i; For (i=0; i<20; i++) { System.out.println (employee[i]); } // no return statement as it’s void } The static keyword means it is a private function. The next keyword is the return type (e.g. int, void, String, float, etc). The next is the name of the function. The input parameters are in brackets. The type of all input values must be specified. Introduction to Object Oriented Programming Classes essentially have attributes (data) and methods (code) associated with them. An object is simply an instance of a class. Classes describe real life entities. For example, a college library could be modelled simply as follows: Class library Attributes: String BookTitle; int BookISBN; Boolean OnLoan; int MemberID; Methods: addBook(string BookTitle, int BookISBN); loanBook(int BookISBN, int memberID); True returnBook(int BookISBN); deleteBook(int BookISBN); // add new book // sets OnLoan to // sets OnLoad to False // deletes an old book Page 3 of 5 HC Computing craig.ian@itsligo.ie Java – Arrays, Functions and Exception Handling Lab 1 Data arrays on Blue Jay. Objectives 1) to understand array basics 2) to become familiar with the basics of object methods. 3) To become aquainted with BlueJ (a Java editor/compiler/tester). The following program will be sent to you by email (KCOMP_C1). /** * Displaying array elements * * Ian Craig * 2 NOV 2006 */ public class Arrays { // instance variables - replace the example below with your own private int x; int[] primes = new int[] {2,3, 5, 7, 11, 13, 17, 19 }; String[] textPrime = new String[] {"two", "three", "five", "seven", "eleven", "thirteen", "seventeen", "nineteen"}; /** * Constructor for objects of class Arrays */ public Arrays() { // initialise instance variables x = 0; } /** * This will print out all prime numbers in the list * * no input parameters * return 0 */ public void printAll() { // // Print the arrays // System.out.println ("Small primes and their English text"); for(int i=0; i<(primes.length); i++) { System.out.println (textPrime[i] + ": " + primes[i]); } } // end /** * Prints a prime from an array * * the index into the array * returns the corresponding prime number or -1 on error */ public int printPrime(int y) { if (y >= (primes.length)) { System.out.println ("Out of range"); return (-1); } else { Page 4 of 5 HC Computing craig.ian@itsligo.ie Java – Arrays, Functions and Exception Handling System.out.println ("The value is for primes[" + y + "] is " + primes[y] + " (" + textPrime[y] + ")"); return (primes[y]); } } } This is a Java program which is based on a class and has two basic methods associated with it, printAll() and printPrime(y). Your job is to test out the two methods in BlueJ and make sure it works. Steps to completion 1. Run up BlueJ. You may need to point it to the correct JDK. 2. Create a New Project on your H drive called primes 3. Create a new class called Arrays (of type class) by clicking on the new class button. 4. Right click on the new class and open with the editor. You will find example template code. 5. Compile this. It will compile ok, but it does not very much. 6. Select and delete it all and copy/paste in the above program. 7. Compile this program. Remove any syntax errors (there may be one or two) Once ok (no syntax errors) 8. Right click again on the arrays class box and choose new Arrays(). This creates an instance of Arrrays, which is shown at the bottom of BlueJ. 9. Right click on the instance and run the method printAll. What happens? Do you expect this? 10 Run the other method printPrime(). This time you are asked for an input value for the index. Enter values of 0, 5, 20 and record what happens. Can you explain the outputs in each case? Modifications a) Modify the program to add three more prime numbers (after 19) to the data sets. Recompile and verify these can be displayed with both methods. Demonstrate the result. b) Add a third method called printName(y), which will take in an integer index and simply print out the corresponding text for the prime number at that index. It will return nothing (void). Test this out. e.g. printName(1); will print out “three” as 3 is the prime at array index 1 i.e. (primes[1]) c) For top marks Create a fourth method called printText(n) which will take in a prime number. The routine or method will find the text name for that prime number on our list and display it. If it is not found, a message to the effect of “prime number not on our list” should be displayed. The method should return with the index value or -1 if not found. e.g printText(13); will print out “thirteen” and return the value 6 Page 5 of 5