Title: Using Predefined Classes and Methods in a Program
1Using Predefined Classes and Methods in a Program
- Many predefined packages, classes, and methods in
Java - Library Collection of packages
- Package Contains several classes
- Class Contains several methods
- Method Set of instructions
2Using Predefined Classes and Methods in a Program
- To use a method you must know
- Name of class containing method (Math)
- Name of package containing class (java.lang)
- Name of method (pow), its parameters (int a, int
b), and function (ab)
3Using Predefined Classes and Methods in a Program
- Example method call
- import java.lang //imports package
- Math.pow(2,3) //calls power method in
//class Math - (Dot) . Operator used to access the method in
the class
4The class String
- String variables are reference variables
- Given String name
- Equivalent Statements
- name new String("Lisa Johnson")
- name Lisa Johnson
5The class String
- The String object is an instance of class string
- The value Lisa Johnson 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
6Commonly Used String Methods
- String(String str)
- char charAt(int index)
- int indexOf(char ch)
- int indexOf(String str, int pos)
- int compareTo(String str)
7Commonly Used String Methods
- String concat(String str)
- boolean equals(String str)
- int length()
- String replace(char ToBeReplaced, char
ReplacedWith) - String toLowerCase()
- String toUpperCase()
8Input/Output
- Input Data
- Format Input
- Output Results
- String Tokenization
- Format Output
- Read From and Write to Files
9Using Dialog Boxes for Input/Output
- Use a graphical user interface (GUI)
- class JOptionPane
- Contained in package javax.swing
- Contains methods showInputDialog and
showMessageDialog - Syntax
- str JOptionPane.showInputDialog(strExpression)
- Program must end with System.exit(0)
10Parameters for the Method showMessageDialog
11JOptionPane Options for the Parameter messageType
12JOptionPane Example
13Tokenizing a String
- class StringTokenizer
- Contained in package java.util
- Tokens usually delimited by whitespace characters
(space, tab, newline, etc) - Contains methods
- public StringTokenizer(String str, String
delimits) - public int countTokens()
- public boolean hasMoreTokens()
- public String nextToken(String delimits)
14Formatting the Output of Decimal Numbers
- Type float defaults to 6 decimal places
- Type double defaults to 15 decimal places
15class Decimal Format
- Import package java.text
- Create DecimalFormat object and initialize
- Use method format
- Example
- DecimalFormat twoDecimal
- new DecimalFormat("0.00")
- twoDecimal.format(56.379)
- Result 56.38
16File Input/Output
- File area in secondary storage used to hold
information - class FileReader is used to input data from a
file - class FileWriter and class PrintWriter send
output to files
17File Input/Output
- Java file I/O process
- Import classes from package java.io
- Declare and associate appropriate variables with
I/O sources - Use appropriate methods with declared variables
- Close output file
18Inputting (Reading) Data from a File
- Use class FileReader
- Specify file name and location
- Create BufferedReader Object to read entire line
- Example
BufferedReader inFile new BufferedReader(new
FileReader("a\\prog.dat"))
19Storing (Writing) Output to a File
- Use class FileWriter
- Specify file name and location
- Utilize methods print, println, and flush to
output data - Example
PrintWriter outFile new PrintWriter(new
FileWriter("a\\prog.out"))
20Skeleton of I/O Program
21Programming Example Movie Ticket Sale and
Donation to Charity
- Input movie name, adult ticket price, child
ticket price, number of adult tickets sold,
number of child tickets sold, percentage of gross
amount to be donated to charity - Output
22Programming Example Movie Ticket Sale and
Donation to Charity
- Import appropriate packages
- Get inputs from user using JOptionPane.showInputDi
alog - Parse and format inputs using DecimalFormat
- Make appropriate calculations
- Display Output using JOptionPane.showMessageDialog
23Movie Ticket Sale and Donation to Charity
- import javax.swing.JOptionPane
- import java.text.DecimalFormat
- public class MovieTicketSale
-
- public static void main(String args)
-
- //Step 1
- String movieName
- String inputStr
- String outputStr
- double adultTicketPrice
- double childTicketPrice
- int noOfAdultTicketsSold
- int noOfChildTicketsSold
- double percentDonation
- double grossAmount
- double amountDonated
- double netSaleAmount
24Movie Ticket Sale and Donation to Charity
- DecimalFormat twoDigits new DecimalFormat("0.00"
) //Step 2 - movieName JOptionPane.showInputDialog
- ("Enter the movie
name") //Step 3 - inputStr JOptionPane.showInputDialog
- ("Enter the price of an adult
ticket") //Step 4 - adultTicketPrice Double.parseDouble(inpu
tStr) //Step 5 - inputStr JOptionPane.showInputDialog
- ("Enter the price of a child
ticket") //Step 6 - childTicketPrice Double.parseDouble(inpu
tStr) //Step 7 - inputStr JOptionPane.showInputDialog
- ("Enter number of adult
tickets sold") //Step 8 - noOfAdultTicketsSold Integer.parseInt(in
putStr) //Step 9 - inputStr JOptionPane.showInputDialog
- ("Enter number of child
tickets sold") //Step 10
25Movie Ticket Sale and Donation to Charity
- grossAmount adultTicketPrice
noOfAdultTicketsSold - childTicketPrice
noOfChildTicketsSold //Step 14 - amountDonated grossAmount
percentDonation / 100 //Step 15 - netSaleAmount grossAmount -
amountDonated //Step 16 - outputStr "Movie Name " movieName
"\n" - "Number of Tickets Sold "
- (noOfAdultTicketsSold
- noOfChildTicketsSold)
"\n" - "Gross Amount "
- twoDigits.format(grossAmount
) "\n" - "Percentage of Gross Amount
Donated " - twoDigits.format(percentDona
tion) "\n" - "Amount Donated "
- twoDigits.format(amountDonat
ed) "\n" - "Net Sale "
- twoDigits.format(netSaleAmou
nt) //Step 17
26Programming Example Student Grade
- Input file containing students first name, last
name, five test scores - Output file containing students first name,
last name, five test scores, average of five test
scores -
27Programming ExampleStudent Grade
- Import appropriate packages
- Get input from file using BufferedReader and
FileReader - Tokenize input from file using StringTokenizer
- Format input and take average of test scores
- Open and write to output file using PrintWriter
and FileWriter - Close files
28STUDENT GRADE
- //Program to calculate average test score.
- import java.io.
- import java.util.
- import java.text.DecimalFormat
- public class StudentGrade
-
- public static void main (String args)
throws IOException, -
FileNotFoundException - //Declare and initialize variables
//Step 1 - double test1, test2, test3, test4, test5
- double average
- String firstName
- String lastName
- StringTokenizer tokenizer
-
29STUDENT GRADE
- BufferedReader inFile new
- BufferedReader(new
FileReader("e\\cecs261/student/test.txt"))
//Step 2 - PrintWriter outFile new
- PrintWriter(new FileWriter("e\\testa
vg.out")) //Step 3 - DecimalFormat twoDecimal
- new
DecimalFormat("0.00") //Step 4 - tokenizer
- new StringTokenizer(inFile.readLine(
)) //Step 5 - firstName tokenizer.nextToken()
//Step 6 - lastName tokenizer.nextToken()
//Step 6 - outFile.println("Student Name "
- firstName " "
lastName) //Step 7
30STUDENT GRADE
- //Step 8-Retrieve five test scores
- test1 Double.parseDouble(tokenizer.nextT
oken()) - test2 Double.parseDouble(tokenizer.nextT
oken()) - test3 Double.parseDouble(tokenizer.nextT
oken()) - test4 Double.parseDouble(tokenizer.nextT
oken()) - test5 Double.parseDouble(tokenizer.nextT
oken()) - outFile.println("Test scores "
- twoDecimal.format(test1)
" " - twoDecimal.format(test2)
" " - twoDecimal.format(test3)
" " - twoDecimal.format(test4)
" " - twoDecimal.format(test5))
//Step 9
31STUDENT GRADE
- average (test1 test2 test3 test4
test5)/5.0 //Step
10 - outFile.println("Average test score "
- twoDecimal.format(average)
) //Step 11 - outFile.close()
//Step 12 -