• No results found

Object-Oriented Programming in Java

N/A
N/A
Protected

Academic year: 2021

Share "Object-Oriented Programming in Java"

Copied!
33
0
0

Loading.... (view fulltext now)

Full text

(1)

CSCI/CMPE 3326

Object-Oriented Programming in Java

Dongchul Kim

Department of Computer Science

University of Texas – Rio Grande Valley

Class, object, member field and method,

final constant, format specifier, file I/O

(2)

Examples - class

class Person { String name; int age; } class Test {

public static void main(String[] args) {

Person p = new Person(); }

(3)

Examples - constructor

class Person {

String name; int age;

Person(String na, int a) {

name = na; age = a; }

}

class Test {

public static void main(String[] args) {

Person p = new Person(); // error }

(4)

Examples - constructor

class Person {

String name; int age;

Person(String na, int a) {

name = na; age = a; }

}

class Test {

public static void main(String[] args) {

Person p = new Person(“Mike”, 18); // no error }

(5)

Examples - method

class Person { String name; int age; void disply_age() { System.out.println(age); } } class Test {

public static void main(String[] args) {

Person p = new Person(); }

(6)

your name

dot operator to access members

class Person { String name; int age; void disply_age() { System.out.println(age); } } class Test {

public static void main(String[] args) {

Person p = new Person(); p.age = 21;

p.display_age(); }

(7)
(8)

Creating Named Constants with

final

Constants keep the program organized and

easier to maintain.

Constants are identifiers that can hold only a

single value.

Constants are declared using the keyword

final.

Constants need not be initialized when

declared; however, they must be initialized

before they are used or a compiler error will be

generated.

(9)

Creating Named Constants with

final

Once initialized with a value, constants cannot

be changed programmatically.

By convention, constants are all upper case

and words are separated by the underscore

character.

For example:

(10)
(11)

Setting the Field Width

A format specifier may also include a field width. Here is an example:

int number = 9;

System.out.printf("The value is

%6d

\n",

number);

The format specifier

%6d

indicates that the argument number should

be printed in a field that is 6 places wide. If the value in number is

shorter than 6 places, it will be right justified. Here is the output of

the code.

The value is 9

If the value of the argument is wider than the specified field width, the field width will be expanded to accommodate the value.

(12)

Using Field Widths to Print

Columns

Field widths can help when you need to print values aligned in

columns. For example, look at the following code

:

int num1 = 97654, num2 = 598; int num3 = 86, num4 = 56012;

int num5 = 246, num6 = 2;

System.out.printf("%7d %7d\n", num1, num2); System.out.printf("%7d %7d\n", num3, num4); System.out.printf("%7d %7d\n", num5, num6);

This code displays the values of the variables in a table with three rows and two columns. Each column has a width of seven spaces. Here is the output for the code:

97654 598

86 56012

246 2

(13)

Printing Formatted

Floating-Point Values

If you wish to print a floating-point value, use the

%f

format specifier.

Here is an example:

double number = 1278.92;

System.out.printf("The number is %f\n", number);

This code produces the following output:

The number is 1278.920000

You can also use a field width when printing floating-point values. For

example the following code prints the value of number in a field that

is 18 spaces wide:

(14)

Printing Formatted

Floating-Point Values

In addition to the field width, you can also specify the

number of digits that appear after the decimal point. Here

is an example:

double grossPay = 874.12;

System.out.printf("Your pay is %.2f\n", grossPay);

In this code, the

%.2f

specifier indicates that the value

should appear with two digits after the decimal point. The

output of the code is:

Your pay is 874.12

1 2

(15)
(16)

File Input and Output

Reentering data all the time could get tedious

for the user.

The data can be saved to a file.

– 

Files can be input files or output files.

Files:

– 

Files have to be opened.

– 

Data is then written to the file.

– 

The file must be closed prior to program termination.

In general, there are two types of files:

– 

binary

(17)

Writing Text To a File

To open a file for text output you create an

instance of the PrintWriter class.

PrintWriter outputFile = new PrintWriter("test.txt");

Pass the name of the file that you

wish to open as an argument to the

PrintWriter constructor.

(18)

The

PrintWriter

Class

The PrintWriter class allows you to write data to a file

using the print and println methods, as you have

been using to display data on the screen.

Just as with the System.out object, the println method

of the PrintWriter class will place a newline character

after the written data.

The print method writes data without writing the newline

character.

(19)

The

PrintWriter

Class

PrintWriter outputFile = new PrintWriter("Names.txt"); outputFile.println("Chris");

outputFile.println("Kathryn"); outputFile.println("Jean"); outputFile.close();

Open the file.

Write data to the file.

(20)

The

PrintWriter

Class

To use the PrintWriter class, put the

following import statement at the top of

the source file:

(21)

Exceptions

• 

When something unexpected happens in a Java

program, an exception is thrown.

• 

The method that is executing when the exception is

thrown must either handle the exception or pass it up

the line.

• 

Handling the exception will be discussed later.

• 

To pass it up the line, the method needs a throws

(22)

Exceptions

To insert a throws clause in a method header,

simply add the word throws and the name of the

expected exception.

PrintWriter objects can throw an

IOException, so we write the throws clause

like this:

public static void main(String[] args)

(23)

Example - PrintWriter

import java.io.*; public class Hello {

public static void main(String[ ] args) throws IOException

{

PrintWriter pw = new PrintWriter("test.txt"); pw.println("Hello, Dr. Kim.");

pw.close(); }

(24)

Appending Text to a File

To avoid erasing a file that already exists,

create a FileWriter object in this manner:

FileWriter fw =

new FileWriter("names.txt", true);

Then, create a PrintWriter object in this

manner:

(25)

Example - FileWriter

import java.io.*; public class Hello {

public static void main(String[ ] args) throws IOException

{

FileWriter fw = new FileWriter("test.txt", true); //PrintWriter pw = new PrintWriter("test.txt");

PrintWriter pw = new PrintWriter(fw); pw.println("Hello, Dr. Kim.");

pw.close(); }

(26)

Specifying a File Location

• 

On a Windows computer, paths contain backslash (\)

characters.

• 

Remember, if the backslash is used in a string, it is a

special character so you must use two of them (\\):

(27)

Specifying a File Location

• 

This is only necessary if the backslash is in a string literal.

• 

If the backslash is in a String object then it will be handled

properly.

• 

Fortunately, Java allows Unix style filenames using the forward

slash (/) to separate directories:

(28)

Reading Data From a File

You use the File class and the Scanner class to

read data from a file:

File

f1

= new

File

(

"Customers.txt"

);

Scanner s1 = new Scanner(

f1

);

Pass the name of the file as an

argument to the File class

constructor.

Pass the File object as an

argument to the Scanner

class constructor.

(29)

Reading Data From a File

Scanner s1 = new Scanner(System.in);

System.out.print("Enter the filename: "); String filename = s1.nextLine();

File file = new File(filename); Scanner s2 = new Scanner(file);

The lines above:

Creates an instance of the Scanner class to read from the

keyboard

Prompt the user for a filename

Get the filename from the user

Create an instance of the File class to represent the file

(30)

Reading Data From a File

• 

Once an instance of Scanner is created, data can be

read using the same methods that you have used to

read keyboard input (nextLine, nextInt,

nextDouble, etc).

// Open the file.

File file = new File("Names.txt");

Scanner s1 = new Scanner(file);

// Read a line from the file.

String str =

s1.nextLine();

// Close the file.

(31)

Example – Read File

import java.io.*;

import java.util.Scanner; public class Hello

{

public static void main(String[] args) throws IOException {

File f1 = new File("C:\\test.txt");

PrintWriter pw = new PrintWriter(new FileWriter(f1,true)); pw.println("Hello, Dr. Kim.");

pw.println("How are you?"); pw.close();

Scanner s1 = new Scanner(f1);

System.out.println(s1.nextLine()+" "+s1.nextLine()); s1.close();

} }

(32)

Exceptions

• 

The Scanner class can throw an IOException when

a File object is passed to its constructor.

• 

So, we put a throws IOException clause in the

header of the method that instantiates the Scanner

class.

(33)

your name

Detecting The End of a File

• 

The Scanner class’s hasNext() method will return true if

another item can be read from the file.

// Open the file.

File file = new File(filename);

Scanner s1 = new Scanner(file);

// Read until the end of the file.

while (

s1.hasNext()

)

{

String str = s1.nextLine();

System.out.println(str);

}

References

Related documents