400 likes | 613 Views
COMP 14 Introduction to Programming. Miguel A. Otaduy May 17, 2004. Last Friday. Variables and expressions Input/output Writing a whole program Any questions?. Today. Classes and objects Graphical user interface (GUI) File input/output Formatting input and output. Classes.
E N D
COMP 14Introduction to Programming Miguel A. Otaduy May 17, 2004
Last Friday • Variables and expressions • Input/output • Writing a whole program Any questions?
Today • Classes and objects • Graphical user interface (GUI) • File input/output • Formatting input and output
Classes • In the Java programming language: • a program is made up of one or more classes • a class contains one or more methods • a method contains program statements
Classes • What is a class? • Data • Operations • Classes allow creation of new data types public class Student { }
Classes Vs. Data Types Concrete Entities • Variable • Object Abstract Descriptors • Data Type • Class
Inside a class • Other classes • Data types • Methods (operations) public class Student {private String name; private int age; public void ComputeGrade(); }
Primitive Variables int x = 45; • x is associated with a memory location. It stores the value 45 • When the computer sees x, it knows which memory location to look up the value in
Reference Variables Integer num; • The memory location associated with num can store a memory address. • The computer will read the address in num and look up an Integer object in that memory location
Creating Objects • We use the new operator to create objects, called instantiation Integer num; num = new Integer(78); parameter
Changing the Reference Var num = new Integer (50); • The address of the newly-created object is stored in the already-created reference variable num
Garbage Collection • What happened to the memory space that held the value 78? • If no other reference variable points to that object, Java will "throw it away"
object Using Objects • System.out object • represents a destination to which we can send output • Example: • printlnmethod System.out.println (”Hello World!”); information provided to the method (parameters) method dot operator
Questions • True or False. A primitive variable is a variable that stores the address of a memory space. • The operator is used to create a class object. • In Java, the operator is used to access members of a class. It separates the class (or object) name from the method name. • True or False. Class objects are instances of that class. False new dot (.) True
The class String • String variables are reference variables • Given String name; • Equivalent Statements: name = new String(“Van Helsing”); name = “Van Helsing”;
name = “Van Helsing”; Van Helsing Van Helsing Van Helsing
The class String • The String object is an instance of class string • The value “Van Helsing” is instantiated • The address of the value is stored in name • The new operator is unnecessary when instantiating Java strings • String methods are called using the dot operator
String(String str) constructor creates and initializes the object char charAt(int index) returns char at the position specified by index(starts at 0) int indexOf(char ch) returns the index of the first occurrence of ch int compareTo(String str) returns negative if this string is less than str returns 0 if this string is the same as str returns positive if this string is greater than str Common String Methods
Common String Methods • boolean equals(String str) • returns true if this string equals str • int length() • returns the length of the string • String replace(char toBeReplaced, char replacedWith) • returns the string in which every occurrence of toBeReplaced is replaced with replacedWith • String toLowerCase() • returns the string that is the the same as this string, but all lower case • String toUpperCase() • returns the string that is the same as this string, but all upper case
String Examples String str = “Van Helsing"; System.out.println (str.length()); System.out.println (str.charAt(2)); System.out.println (str.indexOf(‘s'); System.out.println (str.toLowerCase()); 11 n 7 van helsing
Using Dialog Boxes for I/O • Use a graphical user interface (GUI) • class JOptionPane • Contained in package javax.swing • showInputDialog • allows user to input a string from the keyboard • showMessageDialog • allows the programmer to display results • Program must end with System.exit(0);
JOptionPane Methods • showInputDialog str = JOptionPane.showInputDialog(strExpression); • stores what the user enters into the String str • showMessageDialog JOptionPane.showMessageDialog(parentComponent, strExpression, boxTitleString, messageType);
showMessageDialog • parentComponent • parent of the dialog box • we'll use null • StrExpression • what you want displayed in the box • boxTitleString • title of the dialog box • messageType • what icon will be displayed
messageType • JOptionPane.ERROR_MESSAGE • error icon • JOptionPane.INFORMATION_MESSAGE • information icon • JOptionPane.PLAIN_MESSAGE • no icon • JOptionPane.QUESTION_MESSAGE • question mark icon • JOptionPane.WARNING_MESSAGE • exclamation point icon
JOptionPane Example JOptionPane.showMessageDialog (null, "Hello World!", "Greetings", JOptionPane.INFORMATION_MESSAGE);
Reading From Text Files • Similar to reading from the keyboard • Create a BufferedReader object, but use a FileReader object instead of InputStreamReader • Create BufferedReader object inside the main method instead of outside • Substitute the name of the file for System.in • When finished reading from the file, we need to close the file: • BufferedReader close() method
Reading From Text Files String file = "data.dat"; BufferedReader inFile = new BufferedReader (new FileReader (file)); String line = inFile.readLine(); inFile.close();
Exceptions • FileNotFoundException • if the file specified to open was not found • IOException • some other I/O exception public static void main (String[] args) throws FileNotFoundException, IOException
Writing To Text Files • Similar to reading from text files • Use FileWriter and PrintWriter instead of FileReader and BufferedReader • PrintWriter • methods include print() and println(), just like those we used in System.out • Like reading, we need to close the file when we're done • PrintWriter close() method
Writing To Text Files String file = "outfile.dat"; PrintWriter outFile = new PrintWriter (new FileWriter (file)); outFile.print ("Hi"); outFile.println(" There!"); outFile.close();
User Input • BufferedReader • reads everything as a string • Integer.parseInt • only handles one integer in the string • How to handle? Enter 3 numbers: 34 15 75
The StringTokenizer Class • tokens • elements that comprise a string • tokenizing • process of extracting these elements • delimiters • characters that separate one token from another • StringTokenizer class • defined in the java.util package • used to separate a string into tokens
Tokens and Delimiters “The weekend is over" delimiter: ' ' (space) tokens: “The’’ “weekend’’ “is’’ “over’’ "Bart:Lisa:Homer:Marge" delimiter: ':' tokens: "Bart" "Lisa" "Homer" "Marge"
The StringTokenizerClass • Default delimiters: • space, tab, carriage return, new line • Methods • StringTokenizer (String str) • StringTokenizer (String str, String delimits) • String nextToken() • boolean hasMoreTokens() • int countTokens()
Tokenize.java example • separated by spaces • separated by commas
Formatting the Output of Decimal Numbers • float: defaults to 6 decimal places • double: defaults to 15 decimal places
class DecimalFormat • Import package java.text • Create DecimalFormat object and initialize DecimalFormat fmt = new DecimalFormat (formatString); • FormatString • "0.00" - limit to 2 decimal places, use 0 if there's no item in that position • "0.##" - limit to 2 decimal places, no trailing 0 • Use method format • rounds the number instead of truncating • Result of using DecimalFormat is a String
Examples DecimalFormat twoDecimal = new DecimalFormat("0.00"); DecimalFormat fmt = new DecimalFormat("0.##"); System.out.println (twoDecimal.format(56.379)); System.out.println (fmt.format(56.379)); System.out.println (twoDecimal.format(.3451)); System.out.println (fmt.format(.3451)); System.out.println (twoDecimal.format(.3)); System.out.println (fmt.format(.3)); 56.38 56.38 0.35 0.35 0.30 0.3
To do • Ch. 3 examples: • Movie Ticket Sale • Donation to Charity • Student Grade • Homework 3 due Thursday night. • Read Ch. 4