Chapter 3 Introduction to Objects and Input/Output.

Post on 17-Dec-2015

222 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

Transcript

Chapter 3

Introduction to Objects and Input/Output

Chapter Objectives

• 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

Chapter Objectives

• 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

Object and Reference Variables

• Primitive variables: directly store data into their memory space

• Reference variables: store the address of the object containing the data

Object and Reference Variables

• Declare a reference variable of a class type

• Use the operator new to:– Allocate memory space for data– Instantiate an object of that class type

• Store the address of the object in a reference variable

The Operator new

• Statement:

Integer num;

num = new Integer(78);

• Result:

Garbage Collection

• Change value of num:

num = new Integer(50);

• Old memory space reclaimed

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

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 package

Math.pow(2,3); //calls power method in //class Math

• (Dot) . Operator: used to access the method in the class

The class String

• String variables are reference variables

• Given String name; – Equivalent Statements:

name = new String("Lisa Johnson");

name = “Lisa Johnson”;

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

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)

Commonly Used String Methods

• String concat(String str)

• boolean equals(String str)

• int length()

• String replace(char ToBeReplaced, char ReplacedWith)

• String toLowerCase()

• String toUpperCase()

Input/Output

• Input Data

• Format Input

• Output Results

• String Tokenization

• Format Output

• Read From and Write to Files

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

Parameters for the Method showMessageDialog

JOptionPane Options for the Parameter messageType

JOptionPane Example

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)

Formatting the Output of Decimal Numbers

• Type float: defaults to 6 decimal places

• Type double: defaults to 15 decimal places

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

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

File Input/Output

• Java file I/O process: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

Inputting (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"));

Storing (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"));

Skeleton of I/O Program

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:

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

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

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

Chapter Summary

• Primitive type variables 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 • Operator new is used to instantiate an object• Garbage collection is reclaiming memory

not being used

Chapter Summary

• To use a predefined method you must know its name and the class and package it belongs to

• The . (dot) operator is used to access a certain method in a class

• Methods of the class string are used to manipulate input and output data

• Dialog boxes can be used to input data and output results• String tokenization can be used to format input strings

from files into data• Data can be read from and written to files• Data can be formatted using class DecimalFormat

top related