comp 110: introduction to programming

36
COMP 110: Introduction to Programming Tyler Johnson Apr 13, 2009 MWF 11:00AM-12:15PM Sitterson 014

Upload: devi

Post on 07-Jan-2016

55 views

Category:

Documents


0 download

DESCRIPTION

COMP 110: Introduction to Programming. Tyler Johnson Apr 13, 2009 MWF 11:00AM-12:15PM Sitterson 014. Announcements. Program 5 Milestone 1 due Wednesday by 5pm. Questions?. Today in COMP 110. Brief Review Finish Inheritance Basic Exception Handling Programming Demo. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: COMP 110: Introduction to Programming

COMP 110:Introduction to Programming

Tyler JohnsonApr 13, 2009

MWF 11:00AM-12:15PMSitterson 014

Page 2: COMP 110: Introduction to Programming

COMP 110: Spring 20092

Announcements

Program 5 Milestone 1 due Wednesday by 5pm

Page 3: COMP 110: Introduction to Programming

COMP 110: Spring 20093

Questions?

Page 4: COMP 110: Introduction to Programming

COMP 110: Spring 20094

Today in COMP 110

Brief Review

Finish Inheritance

Basic Exception Handling

Programming Demo

Page 5: COMP 110: Introduction to Programming

COMP 110: Spring 20095

Review: Overriding Methods

Person has a jump method, so all subclasses have a jump method

Person

Athlete

HighJumper

Skydiver

ExtremeAthlete

XGamesSkater

Page 6: COMP 110: Introduction to Programming

COMP 110: Spring 20096

Review: Overriding Methods

Each subclass has its own jump functionalitypublic class Person {

public void jump() { System.out.println("Whee!");}

}

public class Athlete extends Person {

public void jump() { System.out.println("I jump really well!");}

}

Page 7: COMP 110: Introduction to Programming

COMP 110: Spring 20097

Review: Type Compatibilities

ExtremeAthlete is an AthleteXGamesSkater is a PersonPerson is not necessarily a Skydiver

Person p = new ExtremeAthlete();Legal

Athlete a = new Athlete();Legal

XGamesSkater xgs = new Person();Illegal

Page 8: COMP 110: Introduction to Programming

COMP 110: Spring 20098

Polymorphism

“many forms”

Enables the substitution of one object for another as long as the objects have the same interface

8

Page 9: COMP 110: Introduction to Programming

COMP 110: Spring 20099

Dynamic Binding

public static void jump3Times(Person p) {p.jump();p.jump();p.jump();

}

public static void main(String[] args) {

XGamesSkater xgs = new XGamesSkater();Athlete ath = new Athlete();jump3Times(xgs);jump3Times(ath);

}

Page 10: COMP 110: Introduction to Programming

COMP 110: Spring 200910

Inheritance

Some final things on inheritanceImplementing the equals method

Page 11: COMP 110: Introduction to Programming

COMP 110: Spring 200911

The Class Object

The Java class Object provides methods that are inherited by every class

For exampleequals, toString

These methods should be overridden with methods appropriate for the classes you create

Page 12: COMP 110: Introduction to Programming

COMP 110: Spring 200912

The equals Method

Every class has a default .equals() methodInherited from the class ObjectReturns whether two objects of the class are “equal” in some senseDoes not necessarily do what you want

You decide what it means for two objects of a class you create to be considered equal by overriding the equals method

Perhaps books are equal if the names and page numbers are equalPerhaps only if the names are equalPut this logic inside .equals() method

Page 13: COMP 110: Introduction to Programming

COMP 110: Spring 200913

The equals Method

Object has an equals methodSubclasses should override it

public boolean equals(Object obj) {return (this == obj);

}

What does this method do?Returns whether this has the same address as objThis is the default behavior for subclasses

Page 14: COMP 110: Introduction to Programming

COMP 110: Spring 200914

The equals Method

First try:

public boolean equals(Student std) {return (this.id == std.id);

}

This is overloading, not overridingWe want to be able to test if two Objects are equal

Student

- id: int

+ getID(): int+ setID(int newID): void

Page 15: COMP 110: Introduction to Programming

COMP 110: Spring 200915

The equals Method

Second try

public boolean equals(Object obj) {Student otherStudent = (Student) obj;return (this.id == otherStudent.id);

}

What does this method do?Typecasts the incoming Object to a StudentReturns whether this has the same id as otherStudent

Page 16: COMP 110: Introduction to Programming

COMP 110: Spring 200916

The equals Method

public boolean equals(Object obj) { Student otherStudent = (Student) obj; return (this.id == otherStudent.id);}

Why do we need to typecast?Object does not have an id, obj.id would not compile

What’s the problem with this method?What if the object passed in is not actually a Student?The typecast will fail and we will get a runtime error

Page 17: COMP 110: Introduction to Programming

COMP 110: Spring 200917

The instanceof Operator

We can test whether an object is of a certain class type:

if(obj instanceof Student) {System.out.println("obj is an instance of the class

Student");}

Syntax:object instanceof Class_Name

Use this operator in the equals method

Page 18: COMP 110: Introduction to Programming

COMP 110: Spring 200918

The equals Method

Third trypublic boolean equals(Object obj) {

if ((obj != null) && (obj instanceof Student)) {

Student otherStudent = (Student)obj;

return (this.id == otherStudent.id); }

return false;}

null is a special constant that can be assigned to a variable of a class type – means that the variable does not refer to anything right now

Page 19: COMP 110: Introduction to Programming

COMP 110: Spring 200919

Basic Exception Handling

Section 9.1 in text

Page 20: COMP 110: Introduction to Programming

COMP 110: Spring 200920

Error Handling

Recall from Program 4

Parse a string of the formoperand1 operator operand2

For example "23.55 + 54.43"

We assumed the input was validWhat if it’s not?

Page 21: COMP 110: Introduction to Programming

COMP 110: Spring 200921

Error Handling

Example of invalid input"g23.55 + 54.43"

Your programs would happily parse away and attempt to call

Double.parseDouble("g23.55");

Result?Your program crashes with a “NumberFormatException”

Page 22: COMP 110: Introduction to Programming

COMP 110: Spring 200922

Exceptions

An exception is an object that signals the occurrence of an unusual (exceptional) event during program execution

Exception handling is a way of detecting and dealing with these unusual cases in principled manner i.e. without a run-time error or program crash

Page 23: COMP 110: Introduction to Programming

COMP 110: Spring 200923

Example

Handling divide by zero exceptionsBasketballScores

int score = keyboard.nextInt();int scoreSum = 0;int numGames = 0;

while(score >= 0) {scoreSum += score;numGames++;score = keyboard.nextInt();

}

double average = scoreSum/numGames;

Possible ArithmeticException: / by zero!

Page 24: COMP 110: Introduction to Programming

COMP 110: Spring 200924

Example

We could do thisint score = keyboard.nextInt();int scoreSum = 0;int numGames = 0;

while(score >= 0) {scoreSum += score;numGames++;score = keyboard.nextInt();

}

double average = 0;

if(numGames > 0)average = scoreSum/numGames;

Page 25: COMP 110: Introduction to Programming

COMP 110: Spring 200925

Example

Using Exception Handling (try/catch blocks)

int score = keyboard.nextInt();int scoreSum = 0;int numGames = 0;

while(score >= 0) {scoreSum += score;numGames++;score = keyboard.nextInt();

}

double average = 0;

try {average = scoreSum/numGames;

}catch(ArithmeticException e) {

System.out.println(e.getMessage());System.out.println("Cannot compute average for 0 games");

}

Page 26: COMP 110: Introduction to Programming

COMP 110: Spring 200926

Example

When numGames != 0int score = keyboard.nextInt();int scoreSum = 0;int numGames = 0;

while(score >= 0) {scoreSum += score;numGames++;score = keyboard.nextInt();

}

double average = 0;

try {average = scoreSum/numGames;

}catch(ArithmeticException e) {

System.out.println(e.getMessage());System.out.println("Cannot compute average for 0 games");

}

Page 27: COMP 110: Introduction to Programming

COMP 110: Spring 200927

Example

When numGames == 0int score = keyboard.nextInt();int scoreSum = 0;int numGames = 0;

while(score >= 0) {scoreSum += score;numGames++;score = keyboard.nextInt();

}

double average = 0;

try {average = scoreSum/numGames;

}catch(ArithmeticException e) {

System.out.println(e.getMessage());System.out.println("Cannot compute average for 0 games");

}

Page 28: COMP 110: Introduction to Programming

COMP 110: Spring 200928

The try Block

A try block contains the basic algorithm for when everything goes smoothly

Try blocks will possibly throw an exception

Syntaxtry {

Code_To_Try}

Exampletry {

average = scoreSum/numGames;}

Page 29: COMP 110: Introduction to Programming

COMP 110: Spring 200929

The catch Block

The catch block is used to deal with any exceptions that may occur

This is your error handling code

Syntaxcatch(Exception_Class_Name Catch_Block_Parameter) {

Process_Exception_Of_Type_Exception_Class_Name}Possibly_Other_Catch_Blocks

Examplecatch(ArithmeticException e) {

System.out.println(e.getMessage());System.out.println("Cannot compute average for 0 games");

}

Page 30: COMP 110: Introduction to Programming

COMP 110: Spring 200930

Throwing Exceptions

You can also throw your own exceptionstry {

int score = keyboard.nextInt();int scoreSum = 0;int numGames = 0;

while(score >= 0) { scoreSum += score; numGames++; score = keyboard.nextInt();}

if(numGames <= 0) throw new Exception("Exception: num games is less than 1");

double average = scoreSum/numGames;}catch(Exception e) { //catches any kind of exception

System.out.println(e.getMessage());}

Page 31: COMP 110: Introduction to Programming

COMP 110: Spring 200931

Throwing Exceptions

Syntax

throw new Exception_Class_Name(Possibly_Some_Arguments);

Example

throw new Exception("Exception: num games is less than 1");

or

Exception exceptObject = new Exception("Illegal character.");throw exceptObject;

Page 32: COMP 110: Introduction to Programming

COMP 110: Spring 200932

Exception Objects

An exception is an object

All exceptions inherit the method getMessage() from the class Exception

Example

catch(ArithmeticException e) {System.out.println(e.getMessage());System.out.println("Cannot compute average for 0 games");

}

Page 33: COMP 110: Introduction to Programming

COMP 110: Spring 200933

Java Exception Handling

A try block contains code that may throw an exception

When an exception is thrown, execution of the try block ends immediately

Depending on the type of exception, the appropriate catch block is chosen and executed

If no exception is thrown, all catch blocks are ignored

Page 34: COMP 110: Introduction to Programming

COMP 110: Spring 200934

Programming Demo

Adding Exception Handling to Program 4

If we call Double.parseDouble() with invalid input such as "g23.55", the method will throw a “NumberFormatException”

Catch this exception and signal to the user there was a problem with the input

Page 35: COMP 110: Introduction to Programming

COMP 110: Spring 200935

Programming Demo

Programming

Page 36: COMP 110: Introduction to Programming

COMP 110: Spring 200936

Wednesday

Basic File I/O