Last Time (Midterm Exam!) Before that – methods. Spring 2006

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

Today Quiz in the lab, this week. Assignment 1 due Friday, this week. Continue useful classes from the java.lang package. (We did Math and wrapper classes,
CS102--Object Oriented Programming
Today Quiz solutions are posted on the Grading page. Assignment 2 is posted. Due the first Friday after Reading Week. All about null Start File Input/Output.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Files and Streams CS 21a Chapter 11 of Horstmann.
Fundamental Programming Structures in Java: Strings.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter 9-Text File I/O. Overview n Text File I/O and Streams n Writing to a file. n Reading from a file. n Parsing and tokenizing. n Random Access n.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Chapter 7: Characters, Strings, and the StringBuilder.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Winter 2006CISC121 - Prof. McLeod1 Last Time Wrapper classes JFileChooser (along with JOptionPane, and JColorChooser !) Text File Output.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Today… Quiz 1 Topics and “Rules”. Some useful classes from the java.lang package. Includes: –static methods discussion. –The concept of mutability. Winter.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Today Javadoc. Packages and static import. Viewing API source code. Upcoming Topics: –protected access modifier –Using the debugger in Eclipse –JUnit testing.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Today… StringTokenizer class. Method Overloading. Catching Exceptions (and what they are!). Start Pointers and Aliasing. Winter 2016CMPE212 - Prof. McLeod1.
Today… Style hints for Assignment 1. (Nothing else you need from lecture for assn 1.) Designing and writing methods. Some useful classes from the java.lang.
Winter 2006CISC121 - Prof. McLeod1 Stuff Midterm exam in JEF234 on March 9th from 7- 9pm.
Last Time Reviewed method overloading. A few useful Java classes:
Chapter VII: Arrays.
Chapter 2 Basic Computation
Chapter 7 User-Defined Methods.
Objectives You should be able to describe: Interactive Keyboard Input
Java Primer 1: Types, Classes and Operators
Variables and Primative Types
CMPE212 – Stuff… Assn 2 due next Friday. Winter 2018
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Topics Introduction to File Input and Output
Introduction to C++ Programming
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
CSS 161: Fundamentals of Computing
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
Introduction to Java part 2
Fall 2018 CISC124 12/1/2018 CISC124 Note that the next assignment, on encapsulation, is due next Wednesday at 7pm – not Friday. The next Quiz is not until.
Fall 2018 CISC124 12/3/2018 CISC124 or talk to your grader with questions about assignment grading. Fall 2018 CISC124 - Prof. McLeod Prof. Alan McLeod.
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
CISC124 Assignment 3 due tomorrow at 7pm.
Fall 2018 CISC124 2/15/2019 CISC124 TA names and s will be added to the course web site by the end of the week. Labs start next week in JEFF 155:
Fall 2018 CISC124 2/17/2019 CISC124 Quiz 1 This Week. Topics and format of quiz in last Tuesday’s notes. You are ready for exercises 4 and 5, and assignment.
Fall 2018 CISC124 2/22/2019 CISC124 Quiz 1 This Week. Topics and format of quiz in last Tuesday’s notes. The prof. (me!) will start grading the quiz.
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
CISC101 Reminders All assignments are now posted.
Winter 2019 CMPE212 4/5/2019 CMPE212 – Reminders
Winter 2019 CMPE212 4/7/2019 CMPE212 – Reminders
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Winter 2019 CMPE212 4/17/2019 CMPE212 – Reminders
CMPE212 – Reminders Course Web Site:
Last Time Some discussion of program “efficiency”. Arrays – 1D and 2D
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
Winter 2019 CISC101 4/28/2019 CISC101 Reminders
Winter 2019 CMPE212 5/4/2019 CMPE212 – Reminders
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
Unit 3: Variables in Java
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

Last Time (Midterm Exam!) Before that – methods. Spring 2006 CISC101 - Prof. McLeod

Announcements Assn 2 due tonight. Spring 2006 CISC101 - Prof. McLeod

Today Look at midterm solution. Review method overloading. A few useful Java classes: Other handy System class methods Wrapper classes String class StringTokenizer class Classes for File I/O Spring 2006 CISC101 - Prof. McLeod

Method Overloading A method can have the same name in many different classes (“println”, for example). “Overloading” is when a method name is used more than once within the same class. The rule is that no two methods with the same name within a class can have the same number and/or types of parameters in the method declarations. (The “NOT” rule.) Spring 2006 CISC101 - Prof. McLeod

Method Overloading - Cont. Why bother? – Convenience! Allows the user to call a method without requiring him to supply values for all the parameters. One method name can be used with many different types and combinations of parameters. Allows the programmer to keep an old method definition in the class for “backwards compatibility”. Spring 2006 CISC101 - Prof. McLeod

Method Overloading - Cont. How does it work? Java looks through all methods until the parameter types match with the list of arguments supplied by the user. If none match, Java tries to cast types in order to get a match. (Only “widening” casting like int to double, however.) Spring 2006 CISC101 - Prof. McLeod

Method Overloading - Cont. Final notes on overloading: You can have as many overloaded method definitions as you want, as long as they are differentiated by the type and/or number of the parameters listed in the definition. Note that you cannot use the return type to differentiate overloaded methods. Spring 2006 CISC101 - Prof. McLeod

Method Exercise 2 Add a method (called average) to the class containing your main method that returns, as a double, the average of an array of ints supplied as a parameter. This method should also take two more parameters: the starting and finishing positions in the array, over which to carry out the calculation. Write an overloaded version of this same method that only has one parameter – just the array. Note that this method only needs one line of code… Spring 2006 CISC101 - Prof. McLeod

Method Exercise 2, Cont. Test the operation of both methods using an array literal. Spring 2006 CISC101 - Prof. McLeod

Other Classes in Java Classes we have used so far: System Math Scanner JOptionPane Java has hundreds of other classes scattered over many different libraries (or “packages”) We don’t have time to visit them all, but… Spring 2006 CISC101 - Prof. McLeod

System Class We have used: .out object (with print, println and printf methods) .in object (as a parameter to the Scanner class’ instantiation) .exit(0) (to halt a program) Spring 2006 CISC101 - Prof. McLeod

Other Useful System Class Methods System.currentTimeMillis() Returns, as a long, the number of milliseconds elapsed since midnight Jan. 1, 1970. System.getProperties() All kinds of system specific info - see the API. System.getProperty(string) Displays single system property. System.nanoTime() Time in nanoseconds (? Does this work ?) Spring 2006 CISC101 - Prof. McLeod

Wrapper Classes Sometimes it is necessary for a primitive type value to be an Object, rather than just a primitive type. Some data structures only store Objects. Some Java methods only work on Objects. Wrapper classes also contain some useful constants and a few handy methods. Spring 2006 CISC101 - Prof. McLeod

Wrapper Classes - Cont. char Character int Integer long Long float Each primitive type has an associated wrapper class: Each wrapper class Object can hold the value that would normally be contained in the primitive type variable, but now has a number of useful static methods. char Character int Integer long Long float Float double Double Spring 2006 CISC101 - Prof. McLeod

Integer Wrapper Class - Example Integer number = new Integer(46);//”Wrapping” Integer num = new Integer(“908”); Integer.MAX_VALUE // gives maximum integer Integer.MIN_VALUE // gives minimum integer Integer.parseInt(“453”) // returns 453 Integer.toString(653) // returns “653” number.equals(num) // returns false int aNumber = number.intValue(); // aNumber is 46 – “Unwrapping” Spring 2006 CISC101 - Prof. McLeod

Aside - Why an “equals” Method for Objects? The String class also has “equals” and “equalsIgnoreCase”. These wrapper classes also have an equals method. Why not use the simple boolean comparators (==, !=, etc.) with Objects? These comparators just compare memory addresses. How are you going to sort Objects? Spring 2006 CISC101 - Prof. McLeod

Aside - Why an “equals” Method for Objects?, Cont. == can only compare memory addresses when Objects are compared. Most Data Container Objects will have both an equals method and a compareTo method. The equals method tests for equality using whatever you define as “equal”. The compareTo method returns a postive or negative int value (or zero to indicate “equal”), again depending on how you define one Object to be greater or less than another. Spring 2006 CISC101 - Prof. McLeod

Wrapper Classes – Cont. The Double wrapper class has equivalent methods: Double.MAX_VALUE // gives maximum double value Double.MIN_VALUE // gives minimum double value Double.parseDouble(“0.45E-3”) // returns 0.45E-3 parseDouble is only available in Java 2 and newer versions. Spring 2006 CISC101 - Prof. McLeod

Character Wrapper Class Many useful methods to work on characters: “character” is a char getNumericValue(character) isDigit(character) isLetter(character) isLowerCase(character) isUpperCase(character) toLowerCase(character) toUpperCase(character) Spring 2006 CISC101 - Prof. McLeod

Wrapper Classes – Summary Wrapper classes serve a dual purpose: They can wrap primitive types to make objects out of them. The have useful static methods. See the API documentation for more detail on wrapper classes. Spring 2006 CISC101 - Prof. McLeod

String Class, So Far String literals: “Press <enter> to continue.” String variable declaration: String testStuff; or: String testStuff = “A testing string.”; String concatenation (“addition”): String testStuff = “Hello”; System.out.println(testStuff + “ to me!”); Would print the following to the console window: Hello to me! Spring 2006 CISC101 - Prof. McLeod

String Class, So Far - Cont. Note that including another type in a String concatenation calls an implicit “toString” method. So, in: System.out.println(“I am “ + 2); the number 2 is converted to a String before being concatenated. Spring 2006 CISC101 - Prof. McLeod

String Class, So Far – Cont. Escape sequences in Strings: These sequences can be used to put special characters into a String: \” a double quote \’ a single quote \\ a backslash \n a linefeed \r a carriage return \t a tab character Spring 2006 CISC101 - Prof. McLeod

String Class, So Far – Cont. For example, the code: System.out.println(“Hello\nclass!”); prints the following to the screen: Hello class! Spring 2006 CISC101 - Prof. McLeod

String Class, Methods Since String’s are Objects they can have methods. String methods include: length() equals(OtherString) equalsIgnoreCase(OtherString) toLowerCase() toUpperCase() trim() charAt(Position) substring(Start) substring(Start, End) Spring 2006 CISC101 - Prof. McLeod

String Class, Methods – Cont. indexOf(SearchString) replace(oldChar, newChar) startsWith(PrefixString) endsWith(SuffixString) valueOf(integer) String’s do not have any attributes. See the API Docs for details on all the String class methods. String class methods are not static, so you must invoke them from a String object. Spring 2006 CISC101 - Prof. McLeod

String Class - Cont. Examples: int i; boolean aBool; String testStuff = “A testing string.”; i = testStuff.length(); // i is 17 aBool = testStuff.equals(“a testing string.”); // aBool is false aBool = testStuff.equalsIgnoreCase(“A TESTING STRING.”); // aBool is true Spring 2006 CISC101 - Prof. McLeod

String Class - Cont. char aChar; aChar = testStuff.charAt(2); // aChar is ‘t’ i = testStuff.indexOf(“test”); // i is 2 Spring 2006 CISC101 - Prof. McLeod

Aside - More about String’s Is “Hello class” (a String literal) an Object? Yup, “Hello class!”.length() would return 12. String’s are actually stored as arrays of char’s. So, a String variable is actually just a pointer to an array in memory. Spring 2006 CISC101 - Prof. McLeod

StringTokenizer class This useful class is in the “java.util” package, so you need to have an import java.util.*; or import.java.util.StringTokenizer; statement at the top of your program. This class provides an easy way of parsing strings up into pieces, called “tokens”. Tokens are separated by “delimiters”, that you can specify, or you can accept a list of default delimiters. Spring 2006 CISC101 - Prof. McLeod

StringTokenizer class - Cont. The constructor method for this class is overloaded. So, when you create an Object of type StringTokenizer, you have three options: new StringTokenizer(String s) new StringTokenizer(String s, String delim) new StringTokenizer(String s, String delim, boolean returnTokens) Spring 2006 CISC101 - Prof. McLeod

StringTokenizer class - Cont. s is the String you want to “tokenize”. delim is a list of delimiters, by default it is: “ \t\n\r” or space, tab, line feed, carriage return. You can specify your own list of delimiters if you provide a different String for the second parameter. Spring 2006 CISC101 - Prof. McLeod

StringTokenizer class - Cont. If you supply a true for the final parameter, then delimiters will also be provided as tokens. The default is false - delimiters are not provided as tokens. Spring 2006 CISC101 - Prof. McLeod

StringTokenizer class - Cont. Creating a StringTokenizer Object, for example: String aString = "This is a String - Wow!"; StringTokenizer st = new StringTokenizer(aString); Now the Object st has inherited a bunch of useful methods from the StringTokenizer class. Spring 2006 CISC101 - Prof. McLeod

StringTokenizer class - Cont. Here is example code using the methods: String aString = "This is a String - Wow!"; StringTokenizer st = new StringTokenizer(aString); System.out.println("The String has " + st.countTokens() + " tokens."); System.out.println("\nThe tokens are:"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } // end while Spring 2006 CISC101 - Prof. McLeod

StringTokenizer class - Cont. Screen output: The String has 6 tokens. The tokens are: This is a String - Wow! Spring 2006 CISC101 - Prof. McLeod

Aside - Scanner Class Also has a built-in tokenizer. We’ll use this tokenizer when reading text files. Spring 2006 CISC101 - Prof. McLeod

StringTokenizer Example See SystemPropertiesDemo.java. String allProperties = System.getProperties().toString(); System.out.println("\nTokenized string:"); StringTokenizer st = new StringTokenizer(allProperties, ","); while (st.hasMoreTokens()) System.out.println(st.nextToken()); Spring 2006 CISC101 - Prof. McLeod

File I/O Files provide a convenient way to store and re-store to memory larger amounts of data. We will use arrays to store the data in memory, and we’ll talk about these things later. Three kinds of file I/O to discuss: Text Binary Random access For now, we’ll stick with text I/O. Spring 2006 CISC101 - Prof. McLeod

Text File Output in Java 5.0 Use the PrintWriter class. (As usual), you must import the class: import java.io.PrintWriter; In your program: PrintWriter fileOut = new PrintWriter(outFilename); (outFilename is a String filename we obtained somewhere else…) Spring 2006 CISC101 - Prof. McLeod

Text File Output in Java 5.0, Cont. Unfortunately the instantiation of the PrintWriter object can cause a FileNotFoundException to be thrown and you must be ready to catch it: try { writeFile = new PrintWriter(outputFile); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(0); } // end try catch Spring 2006 CISC101 - Prof. McLeod

Aside – Try/Catch Blocks I’ve been avoiding them… An Exception is another way for a method to provide output – in particular an error condition. Exceptions are not “returned” by a method, instead you have to write code to catch them. You only catch an exception when there is some kind of error condition. To catch an exception you must use a “Try/Catch” block: Spring 2006 CISC101 - Prof. McLeod

Aside – Try/Catch Blocks, Cont. Syntax of a “try-catch block”: try { // block of statements that might // generate an exception } catch (exception_type identifer) { // block of statements }[ catch (exception_type identifer) { … }][ finally { }] Spring 2006 CISC101 - Prof. McLeod

Aside – Try/Catch Blocks, Cont. You must have at least one “catch block” after the “try block” (otherwise the try block would be useless!) You can have many catch blocks, one for each exception you are trying to catch. The code in the “finally” block is always executed, whether an exception is thrown, caught, or not. Spring 2006 CISC101 - Prof. McLeod

Aside – Try/Catch Blocks, Cont. A method can throw more than one kind of exception. Why would you want to do this? You can also include more than one line of code that can throw an exception inside a try block. Why would you not want to do this? Spring 2006 CISC101 - Prof. McLeod

Aside – Try/Catch Blocks, Cont. There are two kinds of exceptions: “checked” and “un-checked” “Checked” exceptions must be caught – so you must enclose the method that throws a checked exception in a try/catch block – the compiler will force you to do so. The PrintWriter() constructor throws this kind of exception, so we have to use a try/catch block. The Scanner class’ nextInt() method throws an InputMismatchException that you don’t have to catch. Spring 2006 CISC101 - Prof. McLeod

How to Avoid the Pain!! The java compiler will tell you if you are attempting to execute code that must be in a try/catch block. In Eclipse select the line of code that must be put in a try/catch block, then: Choose “Source” from the main menu, then Choose “Surround with try/catch Block” Spring 2006 CISC101 - Prof. McLeod

Aside – Try/Catch Blocks, Cont. What to do inside the catch block? Message to the user describing error. If you cannot easily fix the problem, then exit the program. Exceptions and try/catch blocks are not part of the CISC101 syllabus, so they will never be on an exam! However, for file I/O many problems with files can be encountered! Spring 2006 CISC101 - Prof. McLeod

Back to Text File Output in Java 5.0 Unfortunately the instantiation of the PrintWriter object can cause a FileNotFoundException to be thrown and you must be ready to catch it: try { writeFile = new PrintWriter(outputFile); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(0); } // end try catch Spring 2006 CISC101 - Prof. McLeod

Aside - File Paths in Strings Sometimes you might have to include a path in the filename, such as “C:\Alan\CIS101\Demo.txt” Don’t forget that if you have to include a “\” in a String, use “\\”, as in: “C:\\Alan\\CISC101\\Demo.txt” Spring 2006 CISC101 - Prof. McLeod

Text File Output in Java 5.0, Cont. The Object writeFile, owns a couple of familiar methods: print() and println(). When you are done writing, don’t forget to close the file with: writeFile.close(); Way easy!! Spring 2006 CISC101 - Prof. McLeod

Text File Input in Java 5.0 Use the FileReader and Scanner classes. Our usual import statements: import java.util.Scanner; import java.io.FileReader; import java.io.FileNotFoundException; We’ll get to that last one in a minute. Spring 2006 CISC101 - Prof. McLeod

Text File Input in Java 5.0, Cont. In a program: fileIn = new FileReader("Test.txt"); Scanner fileInput = new Scanner(fileIn); Unfortunately the FileReader constructor (what’s a “constructor” anyways?) throws a kind of exception that cannot be ignored - so the code above cannot be used exactly in this way. Spring 2006 CISC101 - Prof. McLeod

Text File Input in Java 5.0, Cont. This works: FileReader fileIn = null; try{ fileIn = new FileReader("Test.txt"); } catch (FileNotFoundException e) { // Do something useful here? Scanner fileInput = new Scanner(fileIn); Spring 2006 CISC101 - Prof. McLeod

Text File Input in Java 5.0, Cont. To get the file contents, and print them to the console, for example: while (fileInput.hasNextLine()) { System.out.println(fileInput.nextLine()); } Spring 2006 CISC101 - Prof. McLeod

Aside - Scanner Class’ Tokenizer The Scanner class has a built in String Tokenizer. Set the delimiters using the useDelimiter(delimiter_String) method. Obtain the tokens by calling the next() method. The hasNext() method will return false when there are no more tokens. Spring 2006 CISC101 - Prof. McLeod

Text File I/O Sample Programs TextFileIODemo.java Saves a file with text provided by the user and then opens the file again and displays the contents to the screen. TextFileIODemoWithChooser.java Same program as above except the use of the JFileChooser class is demonstrated as an alternate means of getting a filename from the user. Spring 2006 CISC101 - Prof. McLeod

Without using FileReader You can also send a File object to the Scanner class when you instantiate it instead of a FileReader object. You will still need to do this in a try catch block as shown in the previous slide. See the second demo program. Spring 2006 CISC101 - Prof. McLeod

The File Class File is a class in the java.io.* package. It contains useful utility methods that will help prevent programs crashing from file errors. For example: File myFile = new File(“test.dat”); myFile.exists(); // returns true if file exists myFile.canRead(); // returns true if can read from file myFile.canWrite(); // returns true if can write to file Spring 2006 CISC101 - Prof. McLeod

The File Class, Cont. myFile.delete(); // deletes file and returns true if successful myFile.length(); // returns length of file in bytes myFile.getName(); // returns the name of file (like “test.dat”) myFile.getPath(); // returns path of file (like “C:\AlanStuff\JavaSource”) Spring 2006 CISC101 - Prof. McLeod

The File Class, Cont. All of these methods can be used without having to worry about try/catch blocks, which is nice! See the second demo program for a few examples of File class method use. Spring 2006 CISC101 - Prof. McLeod

Binary and Random Access Binary files contain data exactly as it is stored in memory – you can’t read these files in Notepad! Text file is sequential access only. What does that mean? Random access can access any byte in the file at any time, in any order. More about Binary and Random File Access later! Spring 2006 CISC101 - Prof. McLeod