Chapter 3Prensent

advertisement

Notes adopted from “Java Programming-Thomson Learning”

Chapter 3

Introduction to Objects and Input/Output

Chapter Overview

In this chapter, students will learn more about input and output and how to use predefined classes in programs. They will also learn more about the class string and how it can be used to manipulate strings, input data and output results.

Chapter Objectives

In this chapter, students will:

• Learn about objects and reference variables

• Explore how to use predefined methods in a program

• Become familiar with the class String

• Learn how to use input and output dialog boxes in a program

• Learn how to tokenize the input stream

• Explore how to format the output of decimal numbers with the class DecimalFormat

• Become familiar with file input and output

Objects and Reference Variables

There are t wo types of variables in Java – primitive type variables and reference variables.

Primitive type variables directly store data into their memory space. Reference variables store the address of the object containing the data. An object is an instance of a class and the operator new is used to instantiate an object.

A declaration statement allocates memory for a variable; the operator new however, is used to allocate memory for the actual data. For example the following statements use the operator new to allocate memory space to store an integer with value 78.

Integer num; num = new Integer(78);

The following statement would change the value of num.

Chapter3_1

Notes adopted from “Java Programming-Thomson Learning” num = new Integer(50);

The operator new again would allocate memory space to store an integer; 50 would be stored into the allocated memory space; and the address of the allocated memory space, returned by the operator new, would be stored in num. However, the address of the allocated memory space will be different than that in the first statement. As a result, Java provides a method of garbage collection to automatically reclaim memory space that is not being used.

If you don’t want to depend on Java’s automatic garbage collection system, the statement System.gc(); can be used in a program to run the garbage collector.

Using Predefined Classes and Methods in a Program

Java provides a set of predefined classes. Within these classes, predefined methods exist that can be used to accomplish many programming tasks. Classes exist in defined packages. There are two types of methods in a class – static and non-static. A static method can be called using the name of the class containing the method.

To use a predefined method, you must know the name of the method, as well as the class and package it belongs to.

A method must be called in order to be executed. The . (dot) operator is used to access a method. It

(the dot) separates the class name from the method name.

For example, to use the power method (pow) found in the class Math, you first import the package containing the class Math (import java.lang;) and then call the power method with the appropriate parameters -- Math.pow(2, 3); This call will compute 2^3.

Ref OHP pg9

The class String

Given, String name ; the statement name = “Lisa Johnson”; is equivalent to name = new String(“Lisa

Johnson”);

String variables are reference variables. The string object is an instance of the class String. As a result, when these lines are executed, the String object with the value “Lisa Johnson” is instantiated. The location of the object where this string is stored is then stored to name. The statement name = “Lisa

Johnson”; can be used in place of name = new String(“Lisa Johnson”); because the class String defines the assignment operator in Java.

Therefore, the new operator can be eliminated and the assignment operator can be used to instantiate a string.

The class String provides many methods for manipulating strings. A String variable invokes a String method using the dot operator, the method name, and any arguments required by the method. Some of these methods include:

Chapter3_2

Notes adopted from “Java Programming-Thomson Learning”

String(String str) char charAt(int index) int indexOf(char ch) int indexOf(char ch, int pos) int indexOf(String str) int indexOf(String str, int pos) int compareTo(String str) String concat(String str) boolean equals(String str) int length()

String toLowerCase() String toUpperCase()

String substring(int startIndex, int endIndex)

String replace(char charToBeReplaced, char charReplaceWith)

In order for the substring method to work, it must know the position of the first character and last character of the substring being determined in the string str.

Input/Output

Two basic operations of a program are inputting data and outputting results. There are several says of inputting data and outputting results. One way is through the (1)use of the class BufferedReader and

System.out.

Another way is through the (2)use of dialog boxes, a graphical user interface provided by the class JOptionPane in the javax.swing package. The method showInputDialog in this class is used to get the user input from the keyboard.

The syntax of these two methods is: str = JOptionPane.showInputDialog(strExpression); where str is a String and strExpression is an expression evaluating to a string. When this statement is executed, a dialog box prompting the user to enter input appears on the screen.

The method showMessageDialog is used to display results. The syntax for this method is str = JOptionPane.showMessageDialog(parentComponent, messageStringExpression, boxTitleString, messageType); where parentComponent is an object that represents the parent of the dialog box (null for now) , messageStringExpression is evaluated and its value appears in the dialog box, boxTitleString represents the title of the dialog box, and messageType is an int representing the type of icon that will appear in the dialog box. Different messageTypes include: JOptionPane.ERROR_MESSAGE,

JOptionPane.INFORMATION_MESSAGE, JOptionPane.PLAIN_MESSAGE,

JOptionPane.QUESTION_MESSAGE, and JOptionPane.WARNING_MESSAGE.

 refer to OHP pg16, 17 &18

Chapter3_3

Notes adopted from “Java Programming-Thomson Learning”

In order to use the input/output dialog box and properly t erminate program execution, the program must include the statement: System.exit(0);

This section includes several examples using dialog boxes.

Chapter3_4

Notes adopted from “Java Programming-Thomson Learning”

Another basic operation of a program is manipulating data that has been inputted into a program. If the method readLine is used to input data, the data is received as one string.

However, it may be necessary to break the string into meaningful units of data.

This process is known as tokenization.

The class

StringTokenizer, found in the java.util package can be used to tokenize a string.

Tokens are usually delimited by whitespace characters. These include space, tab, newline, etc. Some members of this class are: public StringTokenizer(String str) public StringTokenizer(String str, String delimits) public StringTokenizer(String str, String delimits, boolean tokens) public int countTokens() public boolean hasMoreTokens() public String nextToken() public String nextToken(String delimits)

To tokenize a string, you first need to create a StringTokenizer object and store the string in the created object.

The method nextToken can be used with the object tokenizer to retrieve the next token from the string.

Chapter3_5

Notes adopted from “Java Programming-Thomson Learning”

 refer to Book Pg121 & 122

Formatting output is another basic function of programs. Sometimes floating-point numbers must be output in a specific way. By default, the output of decimal numbers of the type float is up to 6 decimal places, while the default output of decimal numbers of the type double is up to 15 decimal places. To format these numbers in a specific manner the class DecimalFormat is used. The method format in the class is applied to the decimal value to be formatted. First the package java.text is imported. Then the

DecimalFormat object is created and initialized.

DecimalFormat twoDecimal = new DecimalFormat(“0.00”);

Chapter3_6

Notes adopted from “Java Programming-Thomson Learning”

Next the method format is applied: twoDecimal.format(56.379);

This formats the decimal number 56.37

9 as 56.38

File Input/Output

A file is an area in secondary storage use d to hold information. To input data from a file, you use the class FileReader and to output to a file, you use the classes FileWriter and PrintWriter.

These classes contain methods to read data from a file and send the output of a program to a file.

The Java file I/O process consists of the following steps:

1. Import classes from package java.io

2. Declare and associate appropriate variables with I/O sources

3. Use appropriate methods with declared variables

4. Close output file

(A)To input (read) data from a file, you use the class FileReader. You specify the file name and its location and create the BufferedReader object to read in one line at a time. For instance,

BufferedReader inFile = new BufferedReader(new FileReader(“a:\\prog.dat”));

If the input file does not exist a FileNotFound exception is thrown.

(B)To store (write) output to file, you use the class FileWriter and PrintWriter . You specify the file name and its location and utilize the methods print, println or flush to write the data to the file.

Finally, you close the output file.

For instance,

PrintWriter outFile = new PrintWriter(new FileWriter(“a:\\prog.out”));

outFile.close();

Programming Example: Movie Ticket Sale and Donation to Charity

The input to this program consists of the movie name, adult ticket price, child ticket price, number of adult tickets sold, number of child tickets sold, and the percentage of the gross amount to be donated to the charity. The output consists of an information dialog box containing the movie name, total number of tickets sold, the gross amount, percentage of the gross amount to be donated, the actual amount donated, and the net sale.

Chapter3_7

Notes adopted from “Java Programming-Thomson Learning”

To accomplish this task first the appropriate packages are imported. The user is prompted for input using the JOptionPane.showInputDialog method. The input is parsed and formatted using

DecimalFormat.format. The necessary calculations are made and the output is displayed using

JOptionPane.showMessageDialog.

Refer to Book Pg130-135

//Program: 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;

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

Chapter3_8

Notes adopted from “Java Programming-Thomson Learning”

inputStr = JOptionPane.showInputDialog("Enter the percentage of donation");//Step 12

percentDonation = Double.parseDouble(inputStr); //Step 13

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

}

}

Programming Example: Student Grade

The input to this program is a file containing a student’s first name, last name, and five test scores. The output is a file containing the student’s first name, last name, five test scores and average test score.

To accomplish this task, first the appropriate packages are imported. Then the i nput is read from a file using BufferedReader and FileReader. The input is tokenized using StringTokenizer.

The input is formatted and the average of the scores is calculated. A file is opened and the relevant information is

Chapter3_9

Notes adopted from “Java Programming-Thomson Learning” written to it. The files are then closed.

 refer Book Pg136-139

//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;

BufferedReader inFile = new BufferedReader(new FileReader("a:\\test.txt")); //Step 2

PrintWriter outFile = new PrintWriter(new FileWriter("a:\\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

//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) + " "

Chapter3_10

Notes adopted from “Java Programming-Thomson Learning”

+ twoDecimal.format(test3) + " "

+ twoDecimal.format(test4) + " "

+ twoDecimal.format(test5)); //Step 9

average = (test1 + test2 + test3 + test4 + test5)/5.0; //Step 10

outFile.println("Average test score: " + twoDecimal.format(average)); //Step 11

outFile.close(); //Step 12

}

}

Key Terms

Dot notation: using the dot operator to separate the class name from the member or method name.

File: area in secondary storage used to hold information

Index: position of a character in a string

Method: set of instructions

Method call: triggers the use of a method in a program

Parameters: arguments of a method

Predefined classes: existing classes provided by java

Predefined methods: methods in the existing classes provided by java for use

Tokenization: process of breaking a string into meaningful units of data

Chapter3_11

Download