Lecture 8 Input output, Exceptions

background image

Programming Languages

Lecture 8

Input – Output. Exceptions

R. Pełka – Wojskowa Akademia Techniczna

background image

R. Pełka: Programming Languages

2

Niklaus Wirth

Designed and implemented several
programming languages including
Pascal, Modula-2, Oberon

Simple, elegant solutions are more

effective, but they are harder to find
than complex ones, and they require
more time which we too often believe to
be unaffordable

Wrote the paper that popularized the
idea of step-wise refinement

Iterative enhancement

Grow a working program

Not a fan of C++

background image

R. Pełka: Programming Languages

3

Outline

Streams

character streams
byte streams

Console input/output

File I/O

writing to file
reading from file

Exceptions

exception classes in Java
exception handling

Buffered input and output

background image

R. Pełka: Programming Languages

4

Streams

Stream

is an unidirectional data channel

All external peripherals use streams to communicate

printers, modems, keyboards, terminals, CD-ROMs etc.

For reading data

Input streams

Typical methods

read(), readln()

...

For writing data

Output streams

Typical methods

write(char c), writeln(String s)

...

All necessary classes are in the package

java.io

data

data

background image

R. Pełka: Programming Languages

5

Character Streams

Object

Reader

BufferedReader

InputStreamReader

FileReader

Writer

OutputStreamWriter

PrintWriter

BufferedWriter

FileWriter

………

………

Java has many predefined streams for writing and reading

characters

. Most

useful are listed below

background image

R. Pełka: Programming Languages

6

Byte Streams (Binary Streams)

Object

InputStream

FileInputStream

FilterInputStream

BufferedInputStream

FilterOutputStream

FileOutputStream

BufferedOutputStream

DataInputStream

OutputStream

DataOutputStream

PrintStream

... as well as for writing and reading

bytes

. Most useful are listed below

background image

R. Pełka: Programming Languages

7

Screen I/O

A program would not be much use if it did not interact
with the user!

Two possibilities for screen I/O:

GUI (“Graphical User Interface”) – in a separate lecture

Console

Relatively easy and fast way to get textual information from
and to the user, but:

In the “real world”, the console window is mainly used
for development, and in particular, debugging
purposes.

When was the last time you used a commercial, text
only, console application?

background image

R. Pełka: Programming Languages

8

Console and keyboard

We can use console (screen) and keyboard as data
streams

The keyboard is

InputStream

class

System

defines static variable

in

public

class System{ static InputStream

in

; ...}

Console is

PrintStream

class

System

defines the static field

out

public

class System{ static PrintStream

out

; ...}

background image

R. Pełka: Programming Languages

9

Console Output in Java

Also called “

Text Window

”…. We used it in previous lectures many

times

Easy:

System.out.print( Stuff_to_Print );

System.out.println( Stuff_to_Print );

Stuff_to_Print

can be anything - not just a

String

- these two

methods are heavily

overloaded

. What does that mean? Let’s look

up the

println

method in the Java API.

background image

R. Pełka: Programming Languages

10

Console Output in Java

There is also a

System.out.printf()

method that

can be used for format numeric output.

for example:

System.out.printf("Pi is %5.2f", Math.PI);

displays:

System.out.printf("Pi is %5.2f, E is %.5f",

Math.PI, Math.E);

displays:

Pi is 3.14

Pi is 3.14, E is 2.71828

background image

R. Pełka: Programming Languages

11

Console Output in Java

the

printf()

method can also

be used to format dates and
times.

see the API for more information
on format specifiers.

background image

R. Pełka: Programming Languages

12

Console Output in Java

“Escape sequences” can be used to control the
appearance of the output:

\”

a double quote

\’

a single quote

\\

a backslash

\n

a linefeed

\r

a carriage return

\t

a tab character

These can be embedded anywhere in a

String

.

background image

R. Pełka: Programming Languages

13

Console input in Java

You can directly use

InputStream

referring to

System.in

predefined field

But it is easier to use

Scanner

class

has some useful methods for reading data

we have already used

Scanner

in previous lecture

without any knowledge on data streams

background image

R. Pełka: Programming Languages

14

Console Input in Java

The

Scanner

class must be imported using:

import

java.util.Scanner;

In your program:

Scanner input =

new

Scanner(System.in);

Then, you can use the Object

input

, as many times as

you want calling the appropriate method for whatever
primitive type or

String

you want to get from the user.

For example:

System.out.print("Please enter a number: ");

double

aNum = input.nextDouble();

background image

R. Pełka: Programming Languages

15

Console Input in Java

So, what happens when the user is a “dough-head”
again?

we get another exception being thrown:

It would be nice if

nextDouble()

took care of this for

us, but it does not…

We will discuss exception handling later on

java.util.InputMismatchException

background image

R. Pełka: Programming Languages

16

File I/O

Files

provide a convenient way to store and re-store to

memory larger amounts of data.

Three kinds of file I/O:

Text

(characters)

Binary

(bytes)

Random access

We will discuss Text file I/O only. For other kinds of file
I/O, see

Java documentation

background image

R. Pełka: Programming Languages

17

Writing to file

Create the stream to write to file

FileWriter

myLetter =

new

FileWritter(”C:\\Examples\\Jane.txt”);

the file will be

automatically created, or (if already exists)

rewritten (for a new contents)

Write

myLetter.write(”Hello Jane,

\n

need coal

\n

”);

myLetter.write(”Your uncle

\n

Sam”);

Close the file

myLetter.close();

background image

R. Pełka: Programming Languages

18

Writing to file

import

java.io.*;

public

class

LetterToJane{

static void

piszList(){

try

{ FileWriter myLetter =

new

FileWriter(

”C:\\examples\\Jane.txt”

);

myLetter.write(

”Hello Jane\nneed coal\n”

);

myLetter.write(

”always Yours\nuncle Sam”

);

myLetter.close();

}

catch

(IOException e){ }

}

}

DOS needs ”\\”

in a path name

\n – new line

?

* wildcard

background image

R. Pełka: Programming Languages

19

Exceptions

Errors

– eg. division by 0

Exceptions

– abnormal situations

produced by methods, that usually give correct result,
but sometimes fall, eg.

int

find(Object[] mySet, Object x)

usually

find(mySet,x)

returns an index of element

x

, that

was found as a first in a set

mySet

otherwise, when no

x

has been found in

mySet

– an

exception is created

Program should detect (

catch

) exceptions and handle

them in an appropriate way

background image

R. Pełka: Programming Languages

20

Exceptions

To define a method that can generate exception, we use the keyword

throws

in a signature of the method, eg.

Object find(Object[]mySet, Object x)

throws

NotFoundException

{

...

}

Exception can contain additional informations

text

...

other data

So, exceptions are Objects, and Java has appropriate classes of exceptions

Users can also define their own exceptions

background image

R. Pełka: Programming Languages

21

Java exceptions

background image

R. Pełka: Programming Languages

22

Bank crime as an exception

public

class

AlarmException

extends

Exception{

int

kwota;

String zlodziej;

String ofiara;

AlarmException(String zlodziej,String ofiara,

int

kwota){

this

.zlodziej=zlodziej;

this

.ofiara=ofiara;

this

.kwota=kwota;

}

}

Usually in banks everything is ok, but
sometimes one may try to steal money.
We define exception

AlarmException

We want to know

the name of thief
the name of victim
amount of money

background image

R. Pełka: Programming Languages

23

Trap on thieves

void

przelew(Konto odbiorca,

int

kwota)

throws

AlarmException{

if

(kwota >= 0) {

wyplata(kwota);

odbiorca.wplata(kwota);

}

else throw new

AlarmException(

this

.wlasciciel,

odbiorca.wlasciciel, -kwota);

}

Thieves would try to steal money by transfers of
negative sum of money

The trap activating exceptions may look like this:

background image

R. Pełka: Programming Languages

24

To manage or to exit

There are two ways of exceptions treatment

handling

exceptions within the method, where the

exception occured

try

{ ... }

catch

(...){ ... }

delegating exceptions outside the method

throws

delegation is the simplest way, but when each next
method will do the same, the

run time error

terminates the program with appropriate message.
We used this method in our trap on thieves

background image

R. Pełka: Programming Languages

25

Handling exceptions

public

class

MojeFinanse{

static

String wlasciciel = ”J. Bond”;

static

Konto mojeAktywa =

new

Konto(wlasciciel);

static

Konto akcje =

new

Konto(wlasciciel);

public static

void

sprzedaj(

int

kwota){

try

{

mojeAktywa.przelew(akcje,kwota);

}

catch

(AlarmException k){

System.out.println(

”Zlapany ”

+ k.zlodziej);

System.out.println(

”ukradl ”

+k.kwota+

” ”

+k.ofiara);

}

}

if everything OK

if exception

background image

R. Pełka: Programming Languages

26

More exceptions

Methods can have more exceptions to

delegate

myMethod()

throws

AlarmException, IOException{ ... }

or to handle

try

{...normal processing...}

catch

(AlarmException k) {...handler...}

catch

(IOException e){...handler}

...

finally

{...space for...}

Optional

finally

statement denotes some final actions after all kinds

of exception handling

background image

R. Pełka: Programming Languages

27

... back to : Writing to file

import

java.io.*;

public

class

LetterToJane{

static void

piszList(){

try

{ FileWriter myLetter =

new

FileWriter(

”C:\\examples\\Jane.txt”

);

myLetter.write(

”Hello Jane\nneed coal\n”

);

myLetter.write(

”always Yours\nuncle Sam”

);

myLetter.close();

}

catch

(IOException e){ }

}

}

DOS needs ”\”

in a path name

\n – new line

clear?

* wildcard

background image

R. Pełka: Programming Languages

28

Reading from file

Create the stream to read from file

FileReader aLetter =

new

FileReader(”Jane.txt”);

FileReader

reads data as integers by default

Read the next byte as

int

int number;

number = aLetter.read();

Finish if you get negative number

while(number != -1){..do something..; number=aLetter.read();}

Alternatively, read the next byte as

char

char ch;

ch = (char)aLetter.read();

Close file

aLetter.close();

Besides the

IOException

pay attention to:

FileNotFoundException

background image

R. Pełka: Programming Languages

29

Jane is reading

import

java.io.*;

public

class

JaneReads{

static

void

readAndEcho(){

try

{

FileReader aLetter =

new

FileReader(

”Jane.txt”

);

int

c = aLetter.read();

while

(c != -1){

System.out.print((

char

)c);

c = aLetter.read();

}

aLetter.close();

}

catch

(FileNotFoundException f){}

catch

(IOException e){}

}

}

Hello Jane

need coal

always Yours

uncle Sam

background image

R. Pełka: Programming Languages

30

Dirty tricks

Instead of clear sequence we used before:

int

c = aLetter.read();

while

(c != -1){

System.out.print((

char

)c);

c = aLetter.read();

}

C- and Java-cowboys use to write in shorter form

int

c;

while

(c = aLetter.read() != -1){

System.out.print((

char

)c);

}

c = aLetter.read()

used in the condition of

while

loop reads the next character as a side-effect

background image

R. Pełka: Programming Languages

31

Buffered input and output

reading and writing char by char is not economic

in practice, RAM and hard discs exchange data in larger
blocks

data are

buffered

in the main memory of computer

data

data

background image

R. Pełka: Programming Languages

32

Buffered input and output

When using buffer we can

read

data as follows:

FileReader aData = FileRedaer(

”Jane.txt”

);

BufferedReader aLetter = new BufferedReader(aData);

or, in a one step:

BufferedReader aLetter =

new BufferedReader(new FileReader(

”Jane.txt”

));

Similarly, we can

write

to a buffer:

new

BufferedWriter(

new

FileWriter(

”Jane.txt”

)

background image

R. Pełka: Programming Languages

33

import

java.io.*;

public

class

LetterToJane{

static void

piszList(){

try

{ BufferedWriter myLetter =

new

BufferedWriter(

new

FileWriter(

”Jane.txt”

));

myLetter.write(

”Hello Jane\nhow are You\n”

);

myLetter.write(

”always Yours\nuncle Sam”

);

myLetter.close();

}

catch

(FileNotFoundException f){}

catch

(IOException e){ }

}

}

Pleasant writing

FileWriter

is put

into

BufferedWriter

background image

R. Pełka: Programming Languages

34

... and reading

import

java.io.*;

public

class

JaneReads{

static

void

readAndEcho(){

try

{

BuffereReader aLetter =

new

BufferedReader(

new

FileReader(

”Jane.txt”

));

String line = aLetter.readLine();

while

(line != null){

System.out.println(line);

line = aLetter.readLine();

}

aLetter.close();

}

catch

(FileNotFoundException f){}

catch

(IOException e){}

}

}

Hello Jane

How are You

always Yours

uncle Sam

FileReader

is put

into

BufferedReader

reading line by line

FileNotFoundException

is subclass of

IOException

background image

R. Pełka: Programming Languages

35

Console as a stream

import

java.io.*;

public

class

KeyboardRead{

static

String readln(){

BufferedReader odczyt =

new

BufferedReader(

new

InputStreamReader(System.in));

String line = ””;

try

{ line = odczyt.readLine(); }

catch

{IOException e){ line = e.toString(); }

finally

{

return

line; }

}

static

void

test(){

System.out.println(

”Tell me something nice”

);

String linijka = readln();

System.out.println(

”I repeat:\n

+linijka);

}

}

Tell me something nice

I love You

I repeat:

I love You very much

keyboard

background image

R. Pełka: Programming Languages

36

Summary

Streams

character streams
byte streams

Console input/output

File I/O

writing to file
reading from file

Exceptions

exception classes in Java
exception handling

Buffered input and output


Wyszukiwarka

Podobne podstrony:
Ćw 1 Macierze input-output 2
Starter input output
Ćw 1 Macierze input output
Slide Input, Output With Net Framework Class Library Phạm Minh Tuấn
Boratyński, Jakub; Przybyliński, Michał; Świeczewska, Iwona Metody input output wybrane kierunki r
Configuration of input output
File Input and Output
SN7403 1 QUADRUPOLE 2 INPUT POSITIVE NAND GATES WITH OPEN COLLECTOR OUTPUT
Workshop #4 File Input and Output
SN7401 1 QUADRUPOLE 2 INPUT POSITIVE NAND GATES WITH OPEN COLLECTOR OUTPUTS
IR Lecture1
uml LECTURE
lecture3 complexity introduction
196 Capital structure Intro lecture 1id 18514 ppt
Lecture VIII Morphology
benzen lecture
lecture 1
Lecture10 Medieval women and private sphere

więcej podobnych podstron