Objects, methods, the String class, GUI I/O, StringTokenizer, file I/O

advertisement
COMP 14
Introduction to Programming
Adrian Ilie
June 29, 2005
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Yesterday
• Variables and expressions
• Input/output
• Writing a whole program
Any questions?
2
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Today
• Classes and objects
• Graphical user interface (GUI)
• File input/output
• Formatting input and output
3
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
4
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Classes
• What is a class?
♦ Data
♦ Operations
• Classes allow creation of new
data types
public class Student
{
}
5
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Classes Vs. Data Types
Abstract
Descriptors
♦ Data Type
Concrete Entities
♦ Variable
♦ Object
♦ Class
6
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Inside a class
• Other classes
• Data types
• Methods (operations)
public class Student
{
private String name;
private int age;
public void ComputeGrade();
}
7
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
8
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
9
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Creating Objects
• We use the new operator to create
objects, called instantiation
parameter
Integer num;
num = new Integer(78);
10
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Changing the Reference Var
num = new Integer (50);
• The address of the newly-created
object is stored in the already-created
reference variable num
11
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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"
12
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Using Objects
object
• System.out
♦ represents a destination to which we can
send output
• Example:
♦ println
method
System.out.println (”Hello World!”);
object
method
dot operator
13
Adrian Ilie
information provided to
the method
(parameters)
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Questions
14
1.
True or False. A primitive variable is a variable that
False
stores the address of a memory space. ______
2.
new is used to create a class object.
The operator ____
3.
dot (.) operator is used to access
In Java, the ________
members of a class. It separates the class (or
object) name from the method name.
4.
True or False. Class objects are instances of that
True
class. ______
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The class String
• String variables are reference
variables
• Given String name;
♦ Equivalent Statements:
name = new String(“Van Helsing”);
name = “Van Helsing”;
15
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
name = “Van Helsing”;
Van Helsing
Van Helsing
Van Helsing
16
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
17
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Common String Methods
• 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
18
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
19
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
String Examples
String str = “Van Helsing";
System.out.println (str.length());
11
System.out.println (str.charAt(2));
n
System.out.println (str.indexOf(‘s');
System.out.println (str.toLowerCase());
20
Adrian Ilie
7
van helsing
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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);
21
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
JOptionPane Methods
• showInputDialog
str = JOptionPane.showInputDialog(strExpression);
♦ stores what the user enters into the String str
• showMessageDialog
JOptionPane.showMessageDialog(parentComponent,
strExpression,
boxTitleString,
messageType);
22
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
23
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
24
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
JOptionPane Example
JOptionPane.showMessageDialog (null,
"Hello World!",
"Greetings",
JOptionPane.INFORMATION_MESSAGE);
25
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
UsingGUI.java example
26
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
27
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Reading From Text Files
String file = "data.dat";
BufferedReader inFile = new
BufferedReader (new FileReader
(file));
String line = inFile.readLine();
inFile.close();
28
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
29
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
30
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Writing To Text Files
String file = "outfile.dat";
PrintWriter outFile = new PrintWriter
(new FileWriter (file));
outFile.print ("Hi");
outFile.println(" There!");
outFile.close();
31
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
32
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
33
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Tokens and Delimiters
“The weekend is over"
delimiter: ' ' (space)
tokens: “The’’ “weekend’’ “is’’ “over’’
"Bart:Lisa:Homer:Marge"
delimiter: ':'
tokens: "Bart" "Lisa" "Homer" "Marge"
34
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
The StringTokenizer Class
• Default delimiters:
♦ space, tab, carriage return, new line
• Methods
♦
♦
♦
♦
♦
35
StringTokenizer (String str)
StringTokenizer (String str, String delimits)
String nextToken()
boolean hasMoreTokens()
int countTokens()
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Tokenize.java example
• separated by spaces
• separated by commas
36
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Formatting the Output of
Decimal Numbers
• float: defaults to 6 decimal places
• double: defaults to 15 decimal places
37
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
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
38
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Examples
DecimalFormat twoDecimal =
new DecimalFormat("0.00");
DecimalFormat fmt =
new DecimalFormat("0.##");
56.38
System.out.println (twoDecimal.format(56.379)); _______
System.out.println (fmt.format(56.379));
_______
56.38
39
System.out.println (twoDecimal.format(.3451));
System.out.println (fmt.format(.3451));
0.35
_______
0.35
_______
System.out.println (twoDecimal.format(.3));
System.out.println (fmt.format(.3));
0.30
_______
_______
0.3
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
To do
• Ch. 3 examples:
♦ Movie Ticket Sale
♦ Donation to Charity
♦ Student Grade
• Homework 2 due tomorrow.
• Homework 3 due next Tuesday.
• Read Ch. 4
40
Adrian Ilie
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL
Download