1 / 30

Using Predefined Classes and Methods in a Program

Using 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 (a^b). Using Predefined Classes and Methods in a Program. Example method call:import java.lang; //imports packageMath.pow(2,3); //calls power method in //class Math(Dot) . Operator: used to access the method in the class.

parry
Download Presentation

Using Predefined Classes and Methods in a Program

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. Using 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

    2. Using 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 (a^b)

    3. Using 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

    4. The class String String variables are reference variables Given String name; Equivalent Statements: name = new String("Lisa Johnson"); name = “Lisa Johnson”;

    5. The 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

    6. Commonly Used String Methods String(String str) char charAt(int index) int indexOf(char ch) int indexOf(String str, int pos) int compareTo(String str)

    7. Commonly Used String Methods String concat(String str) boolean equals(String str) int length() String replace(char ToBeReplaced, char ReplacedWith) String toLowerCase() String toUpperCase()

    8. Input/Output Input Data Format Input Output Results String Tokenization Format Output Read From and Write to Files

    9. Using 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);

    10. Parameters for the Method showMessageDialog

    11. JOptionPane Options for the Parameter messageType

    12. JOptionPane Example

    13. Tokenizing 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)

    14. Formatting the Output of Decimal Numbers Type float: defaults to 6 decimal places Type double: defaults to 15 decimal places

    15. class 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

    16. File 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

    17. File 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

    18. Inputting (Reading) Data from a File Use class FileReader Specify file name and location Create BufferedReader Object to read entire line Example:

    19. Storing (Writing) Output to a File Use class FileWriter Specify file name and location Utilize methods print, println, and flush to output data Example:

    20. Skeleton of I/O Program

    21. Programming 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:

    22. Programming Example: Movie Ticket Sale and Donation to Charity Import appropriate packages Get inputs from user using JOptionPane.showInputDialog Parse and format inputs using DecimalFormat Make appropriate calculations Display Output using JOptionPane.showMessageDialog

    23. Movie 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;

    24. Movie 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(inputStr); //Step 5 inputStr = JOptionPane.showInputDialog ("Enter the price of a child ticket"); //Step 6 childTicketPrice = Double.parseDouble(inputStr); //Step 7 inputStr = JOptionPane.showInputDialog ("Enter number of adult tickets sold"); //Step 8 noOfAdultTicketsSold = Integer.parseInt(inputStr); //Step 9 inputStr = JOptionPane.showInputDialog ("Enter number of child tickets sold"); //Step 10 noOfChildTicketsSold = Integer.parseInt(inputStr); //Step 11 inputStr = JOptionPane.showInputDialog ("Enter the percentage of donation"); //Step 12 percentDonation = Double.parseDouble(inputStr); //Step 13

    25. Movie 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(percentDonation) + "%\n" + "Amount Donated: $" + twoDigits.format(amountDonated) + "\n" + "Net Sale: $" + twoDigits.format(netSaleAmount); //Step 17 JOptionPane.showMessageDialog(null, outputStr, "Theater Sales Data", JOptionPane.INFORMATION_MESSAGE); //Step 18 System.exit(0); //Step 19 } }

    26. Programming Example: Student Grade Input: file containing student’s first name, last name, five test scores Output: file containing student’s first name, last name, five test scores, average of five test scores

    27. Programming Example: Student 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

    28. STUDENT 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;

    29. STUDENT GRADE BufferedReader inFile = new BufferedReader(new FileReader("e:\\cecs261/student/test.txt")); //Step 2 PrintWriter outFile = new PrintWriter(new FileWriter("e:\\testavg.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

    30. STUDENT GRADE //Step 8-Retrieve five test scores test1 = Double.parseDouble(tokenizer.nextToken()); test2 = Double.parseDouble(tokenizer.nextToken()); test3 = Double.parseDouble(tokenizer.nextToken()); test4 = Double.parseDouble(tokenizer.nextToken()); test5 = Double.parseDouble(tokenizer.nextToken()); outFile.println("Test scores: " + twoDecimal.format(test1) + " " + twoDecimal.format(test2) + " " + twoDecimal.format(test3) + " " + twoDecimal.format(test4) + " " + twoDecimal.format(test5)); //Step 9

    31. STUDENT 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 } }

More Related