CS121: Computer Programming I A) Collections B) File I/O & Error Handling Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors This Week s Agenda (Part A) Card tricks & data types CORE CONCEPT - the array a very useful ingredient Multidimensional arrays There is something called an ArrayList that is actually more useful than an array & we ll get to that soon CS121/IS223 Week 8, Slide 1 CS121/IS223 Week 8, Slide 2 The Games People Play If I randomly deal 5 cards, how do I keep track of all the cards in this hand? 5 separate variables? Argh! Data Types & Structures Functions & methods provide a way to group program statements together Data types & structures provide a way to group variables & organise data benefits are organisation & speed Would I really use 52 variables to model a deck of cards???? i.e. types that hold multiple values CS121/IS223 Week 8, Slide 3 An important data type in most high-level programming languages is the array it groups data into lists You will learn how to create other data structures (e.g. stacks, queues, linked lists, graphs & trees) in later classes CS121/IS223 Week 8, Slide 4 The Array in Java Used for storing collections of data The Array in Java An array is a special kind of Java object It allows you to create a variable that contains a sequence of data items of ONE given type Each item in the array (element) has an index, so an array is a bit like an indexed list of variables Classic example: a deck of cards deck[52] deck[4][13] deck[52] - you could have 52 elements each representing one card deck[4][13] - you could have a 2-dimensional array where the first element represents the suit and the second the face value CS121/IS223 Week 8, Slide 5 CS121/IS223 Week 8, Slide 6 1
What Does an Array Look Like? [10] Indices 0 1 2 3 4 5 6 7 8 9 Values held here 0 1 2 3 4 5 0 1 2 [6] CS121/IS223 Week 8, Slide 7 [3] Simple Array Example If we want to write a program to compute the average mark for all students in this class, we could write the following Java code: int students = 10; double next = 0, sum = 0, average = 0; Scanner scan = new Scanner(System.in); System.out.println( Enter marks: ); for (int count = 0; count < students; count++){ next = scan.nextdouble(); sum = sum + next; average = sum / students; System.out.println( Average: + average); CS121/IS223 Week 8, Slide 8 Example in Action BUT, how do we work out & print all marks below the average? We lost track of all the grades entered! Amnesia? Creating & Accessing an Array Placeholder Java collections double[] marks = new double[10]; Identical to declaring 10 variables of type double: marks[0], marks[1], marks[2] marks[9] Array index starts with 0, NOT 1; Array index ends at array size 1 Assign values: marks[0] = 45, marks[1] = 88 Arrays allow us to save information that we can access later on - they provide an elegant way to declare a collection of related variables Do things: System.out.println(marks[1]); etc. CS121/IS223 Week 8, Slide 9 CS121/IS223 Week 8, Slide 10 What Does marks Look Like? Important Explanation Once declared, can t change size Indices 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 21.2 32.0 77.1 2.8 9.62 6.11 Each slot holds its own unique double value e.g. marks[4] = 2.0; double[] marks = new double[10]; CS121/IS223 Week 8, Slide 11 temp[0] is 21.2 temp[1] is 32.0 temp[2] is 77.1 temp[3] is 2.8 temp[4] is 9.62 temp[5] is 6.11 6 array slots! double[] temp = new double[6] NOT double[] temp = new double[5] CS121/IS223 Week 8, Slide 12 2
Example Continued (i) What Does This Populated Array Look Like? Indices Use Scanner for reading keyboard input here Creating the array for loops are often used to iterate through array items Use array items just like variables 0 1 2 3 4 5 6 7 8 9 45.0 88.0 96.0 77.0 57.0 21.0 84.0 65.0 68.0 71.0 The array called marks Value of the indexed variable marks[8] The indexed variable marks[6] - it is the 7th slot CS121/IS223 Week 8, Slide 13 CS121/IS223 Week 8, Slide 14 Example Continued (ii) You WILL Forget this Use Scanner for reading keyboard input here Now simple to check each grade Remember indexing starts from 0, so the 1 st element is marks[0] & the last element is marks[array_length 1] Remember this when you get array out of bounds errors! CS121/IS223 Week 8, Slide 15 CS121/IS223 Week 8, Slide 16 General Way to Create an Array arraytype[] arrayname = new arraytype[arraylength]; arraytype can be any primitive type or class type - but let us stick with arrays of primitives for now because arrays of objects work differently!!! An array is an object you can ask it its length: arrayname.length marks.length has value 10 Small number of such array methods in Java see the API CS121/IS223 Week 8, Slide 17 Extending the Example Use Scanner for reading keyboard input here Dynamically creates the array size Dynamically deals with indices CS121/IS223 Week 8, Slide 18 3
Initialising Arrays Arrays can be initialised when declared: Initialiser list double[] marks = {98, 34, 66, 78, 45; The size of the array is set to the minimum necessary to hold the values (so 5 here, indexed 0 to 4) Default initialisation is to set every array element to 0: double[] marks = new double[5]; for (int i = 0; i < marks.length; i++) marks[i] = 0; Changing Array Elements You can access & change array elements like any other variable double[] marks = {98, 34, 66, 78, 45; marks[0] = 45 Changes the value of the first array slot to the value of 45, so this is what is now in the array: {45, 34, 66, 78, 45 CS121/IS223 Week 8, Slide 19 CS121/IS223 Week 8, Slide 20 Exercise double temp[] = {55.1, -4.3, 2.0, -33.9, 2.45, -77.89 What is the size (length) of this array? 6 What value is at temp[3]? -33.9 What value is at temp[6]? Out of bounds!!! Write an assignment to change the value of 2.45 to 8.1 temp[4]=8.1; TO DO: See if you can write a loop to find the array slot holding the value 2.45 and when you do, update the slot to hold 8.1 instead Out of Bounds Errors double[] marks = new double[5]; for (int i = 0; i <= marks.length; i++) marks[i] = 100; Here, when i = 5 we try to put the value 100 into marks[5] this location does not exist! Because we count from 0, mark s[4] is actually the last slot - so be careful!!! When we try to access a non-existent array element, we create an out of bounds error What can we do to correct this problem? Use < and not <= CS121/IS223 Week 8, Slide 21 CS121/IS223 Week 8, Slide 22 Exercise An Answer Write a Java program that creates an integer array of 10 elements, then places the numbers 1 to 10 in this array: use a for loop to initialise the array use another for loop to print the contents of the array on a single line Remember array indices start from 0, so you want to put the number 1 in array position 0 Call your file FirstArray.java CS121/IS223 Week 8, Slide 23 CS121/IS223 Week 8, Slide 24 4
Exercise An Answer Write a Java program that creates a character array to store the letters in your first name: make the size of the array the same size as the number of letters in your name initialise the array to contain these letters use a for loop to print out the letters, each on a separate line Remember characters use single quotes j Call your file SecondArray.java CS121/IS223 Week 8, Slide 25 CS121/IS223 Week 8, Slide 26 Exercise Write a Java program that creates a double array to store 15 numbers: write a for loop to ask the user to enter 15 numbers inside this for loop, place each of the entered numbers in the array use another for loop to print out the numbers An Answer Use Scanner for reading keyboard input here Call your file ThirdArray.java CS121/IS223 Week 8, Slide 27 CS121/IS223 Week 8, Slide 28 Multidimensional Arrays As You Would Guess? rows columns How do you think we represent this in a Java program? Apr May June July Aug Sept 2002 21.2 32.0 77.1 2.8 9.62 6.11 2003 2004 24.2 32.0 79.1 12.8 99.62 2.31 31.2 32.0 87.1 86.3 7.62 99.11 2005 91.8 32.0 11.1 3.48 8.14 7.4 CS121/IS223 Week 8, Slide 29 double[][] table = new double[4][6]; This time, you need to use a nested for loop to initialise or print out the array values: for all the rows for all the columns dosomething(to element at index pinpointed by row & column); Initialiser list - values are loaded using nested arrays: {{first_row values, {second row values, etc e.g. {{2.1.2, 32.0, 77.1, 2.8, 9.62, 6.11, etc CS121/IS223 Week 8, Slide 30 5
Example A Java program that puts these values in a 2 -dimensional array, then prints them out 21.2 32.0 77.1 2.8 9.62 6.11 24.2 32.0 79.1 12.8 99.62 2.31 31.2 32.0 87.1 86.3 7.62 99.11 91.8 32.0 11.1 3.48 8.14 7.4 CS121/IS223 Week 8, Slide 31 Example Code Each row separately double[][] table = {{21.2,32.0,77.1,2.8,9.62,6.11, {24.2,32.0,79.1,12.8,99.62,2.31, {31.2,32.0,87.1,86.3,7.62,99.11, {91.8,32.0,11.1,3.48,8.14,7.4; for (int row = 0; row < table.length; row++){ Think in the other dimension! for (int col = 0; col <table[row].length; col++){ System.out.println(table[row][col]); System.out.println(); See - these nested loops come in handy! CS121/IS223 Week 8, Slide 32 NOTE To check whether 2 arrays are equal (i.e. hold the same elements), you need to loop through the arrays checking for the equality of each element at the corresponding index position You can t say (array1 == array2)!? Your loops are critical for manipulating collections, that s why we practice them lots Exercise Write a Java program that keeps a record of how many hours you spent gaming each day over a period of 4 weeks: use a 2-dimensional array prompt the user to enter the hours played for each day in week 1, then in week 2, etc print out the following: Week 1, Day 1: xxx hours of gaming Week 1, Day 2: yyy hours of gaming Call your file GameArray.java Week 4, Day 7: zzz hours of gaming CS121/IS223 Week 8, Slide 33 CS121/IS223 Week 8, Slide 34 Something Similar Challenge Think about it! How about representing a tic-tac-toe board? Use Scanner for reading keyboard input here One dimensional array or two dimensional? How would you place characters & play a game? char[][] tic = new char[3][3] tic[2][2] = x How could you make the computer play to win? AI? TO DO: write a 2 player tic-tac-toe game for me!!! CS121/IS223 Week 8, Slide 35 CS121/IS223 Week 8, Slide 36 6
Hint: Create and Initialise (step 1) char[][] ttt = new char[3][3]; for (int i = 0; i< ttt.length; i++){ for (int j=0; j< ttt[i].length; j++){ ttt[i][j]= ' '; Hint: Hard-wire Populate (step 2) ttt[0][0] = 'x'; ttt[0][1] = 'o'; ttt[0][2] = 'o'; ttt[1][0] = 'x'; ttt[1][2] = 'x'; ttt[2][0] = 'o'; ttt[2][1] = 'o'; ttt[2][2] = 'x'; CS121/IS223 Week 8, Slide 37 CS121/IS223 Week 8, Slide 38 Hint: Print Board (step 3) for (int i = 0; i< ttt.length; i++){ for (int j=0; j< ttt[i].length; j++){ System.out.print(ttt[i][j]); System.out.println(); Another Dimension? 3+ di arrays in Java not recommended NOW change the hardwired bit to accept input and check whether X or O is already in a slot if not, put in in! How would you check for a winner? char[][][] cube = new char[4][5][3] CS121/IS223 Week 8, Slide 39 CS121/IS223 Week 8, Slide 40 Key Points Arrays are a data structure for dealing with a collection of variables of the same type Array indices start from ZERO in Java - never from 1 The last index in an array is always one less than the array length in Java (so, n 1) This Week s Agenda (Part B) Simple error handling & exceptions File input & output: opening, closing, reading & writing Out of bounds errors are a common mistake when using arrays (i.e. trying to access an array element that does not exist) Using arrays, you need to perfect your for loops! CS121/IS223 Week 8, Slide 41 CS121/IS223 Week 8, Slide 42 7
Error Handling Errors 3 main types of error NO! Syntax errors: violation of language s grammatical rules prevents program from running Logic (semantic) errors: flawed algorithms or thinking program runs but doesn t produce the results you expect Runtime errors: error that occurs when a programming is running, due to things like nonsense input program often aborts (crashes) CS121/IS223 Week 8, Slide 43 CS121/IS223 Week 8, Slide 44 Error Detection Most IDEs help you with syntax errors Java raises an exception when it detects a runtime error Logic (semantic) errors you are on your own: so important to get your algorithms right! Exceptions Errors at runtime cause exceptions: division by zero trying to extract a list element that doesn t exist trying to open a file that doesn t exist entering a string when a number is expected It is bad practice to let runtime errors crash your program It is good practice to check for such errors (catch them) & handle them You could write a jumble of code to check for all sorts of conditions, but there is a neater way to do this You have to think about what could go wrong in your program & what to do about it! CS121/IS223 Week 8, Slide 45 CS121/IS223 Week 8, Slide 46 This is a BIG topic & will be looked at more later Error Handling in Java In Java An exception is signalled by a program or runtime environment when it encounters an unusual or incorrect situation this is called throwing an exception Exceptions can be caught & handled by programs this is called handling an exception Exception handling helps you create robust programs & you should use it for potential risky code, where simple conditional checks are not sufficient In Java, there are some built-in exceptions you can use, but you are more likely to need to write your own you do this by writing a class System.exit(0) ends a program CS121/IS223 Week 8, Slide 47 In Java, we use: Try block try { if (denominator==0) throw new DivideByZeroException(); catch(dividebyzeroexception e){ System.out.println( Can t divide by zero ); Catch block An exception is an object of type Exception - You can define your own class of exception, throw them in your programs & catch them! CS121/IS223 Week 8, Slide 48 8
Considerations & Options Options for dealing with issues at runtime: Ignore (duh! But sometimes what can you do?) Handle when encountered (catch it) Handle later (propagate it) An exception is an object of type Exception, you can define your own class of exception using inheritance, throw instances in your programs & catch them - exceptions are polymorphic [LATER!] You may want to deal with multiple types of exception if you want to distinguish many types of problem (i.e. diagnostics) CS121/IS223 Week 8, Slide 49 try catch finally Potentially dodgy code can create & then throw try { different exception objects here if needed whatever; Exception handlers as many as you need for type -specific recovery execution passes to finally clause as soon as one is matched & executed catch(dividebyzeroexception e){ System.out.println( Can t div by 0 ); catch(numberformatexception e){ System.out.println( Not numeric ); finally{ Definitely execute if present Maybe execute (i.e. if type matches) Optional. Executed no matter how the try block is executed System.out.println( I m done ); Can guarantee something happens CS121/IS223 Week 8, Slide 50 Explanation Example in a minute Input & Output If an exception occurs at any point when executing the try block, control is passed to the appropriate catch handler (i.e. the clause whose exception class matches that of the exception thrown) Then, control passes to statement following the entire try..catch block A finally clause just ensures that something always happens irrespective of what went on before (like when you leave the house you always want to make sure you lock the door) Input so far via keyboard Output so far via monitor (print) It is often useful to access files from within a program to read, write & manipulate stored data File I/O We will only look at the basics CS121/IS223 Week 8, Slide 51 CS121/IS223 Week 8, Slide 52 Why Bother With Files? You can deal with larger input & output You can do all sorts of manipulation with the contents of files (they are just strings & lists, so you can traverse, reverse, etc): counting words counting lines This is just the tip of the iceberg for now! changing words changing case finding words adding markup making permanent records CS121/IS223 Week 8, Slide 53 File Input/Output File I/O, as well as simple keyboard & screen I/O, is handled by streams in Java A stream is an object that either: delivers data to a destination (e.g. file or screen) takes data from a source (e.g. file or keyboard) & delivers it to a program System.out object is an output stream for screen output System.in implements the standard input stream that reads characters from the keyboard. CS121/IS223 Week 8, Slide 54 9
What is a Stream? A flow of data (characters, numbers, etc) Input stream data flows into a program Output stream data flows out of a program Streams are implemented as objects of special stream classes in Java (don t worry about the details for now) We will look only at text files for now CS121/IS223 Week 8, Slide 55 You must import this for dealing with file I/O at the start of the class Writing Text to a File (File Output) import java.io.*; Variable of class type PrintWriter PrintWriter outputstream = null; Generally placed inside a try-catch outputstream = new PrintWriter(new FileOutputStream( out.txt )); Preferred stream class for writing to a text file in Java This connects a stream called outputstream to a file called out.txt It creates the file out.txt if it doesn t exist, or opens & overwrites it if it does exist Once created, you can write to the file using familiar statements - outputstream.println( whatever ); & close it using outputstream.close(); CS121/IS223 Week 8, Slide 56 *NOTE import java.util.scanner and make a Scanner object to read stuff in *TRY THIS OUT* Reading Text from a File (File Input) import java.io.*; Variable of type BufferedReader BufferedReader inputstream = new BufferedReader(new FileReader( data.txt )); From [Savitch 2004] Use Scanner methods here See listing 8.9 in ed 3 of text those of you without ed 3 can download code from the text website CS121/IS223 Week 8, Slide 57 Generally placed inside a try-catch The class BufferedReader is the preferred stream class for reading from a text file; class FileReader helps us open a file This connects a text file to a stream of the class BufferedReader to enable your program to read from a file Once open, you can read from the file using familiar statements line = inputstream.readline(); & close it using inputstream.close(); CS121/IS223 Week 8, Slide 58 Sets up the input stream, reads & processes it a line at a time data.txt 1 2 buckle my shoe. 3 4 shut the door. You Read Strings When you read in from data files, you always read in a String String s = inputstream.readline(); *NOTE *TRY THIS OUT* See listings 8.7 & 8.8 (ed 3) in text - it tokenizes the From [Savitch 2004] input & uses it to create objects those of you without CS121/IS223 ed 3 can download code from the text website Week 8, Slide 59 To read in a string & convert to an integer String s = inputstream.readline(); num = Integer.parseInt(s); Wrapper types To read in a string & convert to a double String s = inputstream.readline(); num = Double.parseDouble(s); CS121/IS223 Week 8, Slide 60 10
StringTokenizer Using a StringTokenizer [Lewis & Loftus 2004] Java class used to extract & process data in a string import java.util.stringtokenizer to use it Tokens the name for the individual elements that comprise a string Tokenizing the name we give to the process of extracting elements from a string Delimiters the characters that separate tokens Possible token I want my coffee, now! Possible delimiters you choose them CS121/IS223 Week 8, Slide 61 import java.util.scanner; import java.util.stringtokenizer; public class CountWords{ public static void main (String[] args){ int wordcount = 0, charactercount = 0; String line, word; Scanner scan = new Scanner(System.in); StringTokenizer tokenizer; So you can use the class & its methods Declares a variable of StringTokenizer type System.out.println ("Please enter text (type DONE to quit):"); Makes a StringTokenizer object line = scan.nextline(); while (!line.equals("done")){ tokenizer = new StringTokenizer (line); Checks if tokens in string while (tokenizer.hasmoretokens()){ word = tokenizer.nexttoken(); Gets next token from a string wordcount++; charactercount += word.length(); line = scan.nextline(); System.out.println ("Number of words: " + wordcount); System.out.println ("Number of characters: " + charactercount); Reads several lines of text, counting the number of words & the number of non-space characters CS121/IS223 Week 8, Slide 62 Other Delimiters When you create a StringTokenizer object, state what delimiters you want it to use final String DELIMS = "`~!(){[]\"':;,.?-\n\t "; StringTokenizer tokenizer; String line; tokenizer = new StringTokenizer (line, DELIMS); String to tokenize Final modifier declares a constant String that provides a set of delimiters CS121/IS223 Week 8, Slide 63 Key Points (Part B) Exceptions & file handling are big topics in Java! There are a number of built-in exceptions you can use, but you will need to learn to write your own & understand how they work (requires OO thinking) File I/O is very sophisticated! For now, & until you encounter file I/O further, you need to take a few things on faith & use the standard code - as with public static void main (String[] args) - please explore the API for more info if interested CS121/IS223 Week 8, Slide 64 Before Next Time Reading: if 3 rd edition - read Chapter 6.0 of the Java book; lightly skim sections 8.0 to 8.3 if 4 th - 6 th edition read Chapter 7.1-7.2 of the Java book; lightly skim sections 10.1 to 10.3 Try to keep up with your exercises you should be on exercise sheet 2 and start working on part B Coming Up Next Time An object-oriented primer - thinking with objects! Classes, objects and methods - looking at program structure and control flow Don t forget that the exercise sheets and readings are designed for YOUR practice! CS121/IS223 Week 8, Slide 65 CS121/IS223 Week 8, Slide 66 11