cs 115 object oriented programming i lecture 9 george koutsogiannakis copyright: 2014 illinois...

33
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Upload: scarlett-bates

Post on 18-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

CS 115

OBJECT ORIENTED PROGRAMMING ILECTURE 9

GEORGE KOUTSOGIANNAKIS

Copyright: 2014 Illinois Institute of Technology-George Koutsogiannakis

1

Page 2: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

PREVIOUS TOPICS

• FORMING CONDITIONS FOR SELECTION– RELATIONAL OPERATORS– BOOLEAN EXPRESSIONS- TRUTH TABLES– BOOLEAN OPERATIONS – DE MORGANS LAWS

• if and else SELECTIONS• If else SELECTIONS

2

Page 3: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

NEW TOPICS

• SWITCH SELECTION STRUCTURE.• COMPARING OBJECTS.• COMPARING STRINGS.• STRING TOKENIZER.• CONDITIONAL OPERATOR.

3

Page 4: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

The switch Statement

• In some selection operations, the switch statement can be used instead of an if/else/if statement

• Requirements:– we must be comparing the value of a character

(char) or integer (byte, short, or int) expression to constants of the same types

4

Page 5: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Syntax of switch

switch ( char or integer expression )

{ case constant1: // statement(s);

break; // optional

case constant2:

// statement(s);

break; // optional

default: // optional

statement(s);

}

5

Page 6: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Operation of switch

• The expression is evaluated, then its value is compared to the case constants in order.

• When a match is found, the statements following that case constant are executed in sequence until either a break statement or the end of the switch block is reached. – Thus, once a match is found, if other case constants are

encountered before a break statement, then the statements for these case constants are also executed.

6

Page 7: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Some Finer Points of switch

• The break statements are optional. Their job is to terminate execution of the switch statement.

• The default label and its statements, are also optional. They are executed when the value of the expression does not match any of the case constants.

• The statements under the case constant are also optional, so multiple case constants can be written in sequence if identical operations will be performed for those values.

7

Page 8: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Example: a Simple Calculator

• Prompt user for two doubles (num1, num2) and a char (operation), which can be 'a' for addition or 's' for subtraction

switch ( operation ){

case 'a': result = num1 + num2; break;

case 's': result = num1 - num2; break;

default: System.out.println( "Unrecognized option" );}

8

Page 9: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

A Case-Insensitive Calculator

switch ( operation ){

case 'a': case 'A':

result = num1 + num2; break;

case 's': case 'S':

result = num1 - num2; break;

default: System.out.println( "Unrecognized option" );}

9

Page 10: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Switch and if/else if

• A switch structure with break statements is equivalent to a if/else if blocks of code. The default condition is a single else at the end after the last else if.

10

Page 11: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing objects for Equality

• Suppose that we have template class Student.• In class StudentClient we instantiate two objects

of Student class. Student st1=new Student(); Student st2=new Student();• Can we ask if the two are equal? And do we

mean by equal?

11

Page 12: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing objects for Equalit

• Equal refers to the values of the objects’ attributes. Therefore we want to compare the values of the attributes of the two objects

• Asking for the evaluation :if(st1==st2)

does not compare the objects. Instead it compares the memory addresses that represent those two objects.

12

Page 13: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing Object References

The equality operator (==) compares object references (addresses in memory).

Example: • Suppose that we have a class called SimpleDate.• The class has attributes: month, day, year.• Suppose that we have d1 and d2 as two SimpleDate

object references.• Notice that object refernces refer to declarations

only without the instantiation of the objects i.e.

13

Page 14: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing Object References• SimpleDate d1; SimpleDate d2; The two lines of code above indicates declarations only. At this time d1

and d2 have not been instantiated. The system knows that two memory locations are needed an addresses have been provided but no data has been generated as yet to be stored at these addresses.

• The line of code: if (d1 = = d2)

evaluates to true only if d1 and d2 point to the same object reference, that is, the same memory location.

*** The equality operator does not compare the data (month, day, and year) in those objects.

14

Page 15: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing Object References

• Suppose we instantiate the two references d1 and d2:

d1=new SimpleDate(11, 24, 2009);d2=new SimpleDate(10, 28, 2010);Again the line of code: if (d1= = d2) yields true if

the two addresses in memory (address d1 and address d2 are the same).

15

Page 16: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing Object Data

To compare object data, use the equals method

Example: If st1 and st2 are Student objects, if (st1.equals( st2 )) returns true if the attributes have equal values i.e firstName, lastName,

studentID e.t.c.Or in the case of the SimpleDate class : if (d1.equals(d2))

Return type

Method name and argument list

boolean equals( Object obj )

returns true if the data of the object obj is equal to the data in the object used to call the method; false otherwise

16

Page 17: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing SimpleDate Objects

Suppose that we have 4 SimpleDate objects

17

Page 18: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing SimpleDate Objects

• if(d1==d3) evaluates to true because the two objects have the same address (point to the same memory location).

• if (d1==d2) evaluates to false.• if (d1.equals(d2)) evaluates true because the

attributes of d1 and d2 have the same values.• if (d1.equals(d4)) evaluates to false.

18

Page 19: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

The equals method

• The method equals belongs to a library class called Object.

• Every program that we write is an extension of the library class Object. Therefore it inherits (it gets to use without creating an object to invoke them) all the methods of library class Object.

19

Page 20: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Modifying the equals method

• We can apply our own equals method in a class (usually the template class). – Equals is a method that belongs to Object pre defined

class (library class). – All java objects that we create are also part of the Object

pre defined class (even our template class objects).– This give us the right to use the equals method of the

Object class.• We can modify the equals method in our template class to

provide our own definition of what constitutes equality between two objects of this class.– This is called “method overriding”

20

Page 21: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Modifying equals

• In our template class we introduce the method: public boolean equals(Object_Type o) where Object_Type is the name of the class that the object

belongs to (template class).• Notice that executing this method returns true or false (a

boolean).• Inside the method set up the conditions for equality: i.e. It could be that we define two objects of People class (as

an example) as being equal as long as the current IDs are the same (regardless of the values of the other attributes ). i.e if(this.personID()==o.getpersonID())

return true;21

Page 22: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Comparing Strings

• Strings are objects• Thus, to compare two Strings, use the equals method • Example: s1 and s2 are Strings s1.equals( s2 ) returns true only if each character in s1 matches the

corresponding character in s2• Two other methods of the String class also can be used for

comparing Strings: equalsIgnoreCase

compareTo

22

Page 23: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

The equalsIgnoreCase Method

Example: String s1 = "Exit", s2 = "exit"; if ( s1.equalsIgnoreCase( s2 ) )

System.exit( 0 );

Return type Method name and argument list

boolean equalsIgnoreCase( String str )

compares the value of two Strings, treating uppercase and lowercase characters as equal. Returns true if the Strings are equal; returns false otherwise.

23

Page 24: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

The compareTo Method

A character with a lower Unicode numeric value is considered less than a character with a higher Unicode numeric value. That is, a is less than b and A is less than a. (See Appendix C for Unicode values.)

See Text Example 5.12 ComparingStrings.java

Return type Method name and argument list

int compareTo( String str )

compares the value of the two Strings. If the String object is less than the String argument, str, a negative integer is returned. If the String object is greater than the String argument, a positive number is returned; if the two Strings are equal, 0 is returned.

24

Page 25: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

StringTokenizer Library class

• StringTokenizer class is part of java.util package• The string tokenizer class breaks a string into tokens and

returns the tokens.• Tokens can be defined according to delimiter.

– Delimiters are the characters that separate tokens.– i.e Suppose we have the string “the day is Friday, the week is the

third, the year is 2008”– If we define the delimiter to be the character comma (,) then we have the following tokens: 1st token: “the day is Friday” 2nd token: “the week is the third” 3rd token: “the year is 2008”

25

Page 26: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

StringTokenizer

• StringTokenizer Constructors:– public StringTokenizer(String str) – Constructs a string tokenizer for the specified string. – The tokenizer uses the default delimiter set, which is " \t\n\r\f": the

space character, the tab character, the newline character, the carriage-return character, and the form-feed character.

– Delimiter characters themselves will not be treated as tokens.

– Parameters:str - a string to be parsed.

26

Page 27: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

StringTokenizer

• Another StringTokenizer constructor:– public StringTokenizer(String str, String delim) – Constructs a string tokenizer for the specified string. – The characters in the delim argument is the delimiter for separating

tokens. – Delimiter characters themselves will not be treated as tokens.

– Parameters:str - a string to be parsed.delim - the delimiters.

27

Page 28: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

StringTokenizer

• Methods of StringTokenizer:– public boolean hasMoreTokens() Tests if there are more

tokens available from this tokenizer's string. – If this method returns true, then a subsequent call to

nextToken with no argument will successfully return a token.

– Returns:true if and only if there is at least one token in the string after the current position; false otherwise.

– We will use this method within an if structure as a condition to be evaluated.

28

Page 29: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

StringTokenizer

• public String nextToken()– Returns the next token from this string tokenizer.

29

Page 30: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

StringTokenizer Examplepublic class Tokenize {

`public static void main(String[] args) {

String tokenizeit=args[0];StringTokenizer stk=new StringTokenizer(tokenizeit, ",");int counttok=stk.countTokens():;if(stk.hasMoreTokens()){ //get the first token

String token=stk.nextToken(); System.out.println("The token is:"+token);}if(stk.hasMoreTokens()){

//get the second token String token=stk.nextToken();

System.out.println("The token is:"+token);}

}} //actually we would need a loop to capture all the tokens the easy way!!!

30

Page 31: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

The Conditional Operator (?:)

The conditional operator ( ?: ) contributes one of two values to an expression based on the value of the condition.

• Some uses are – handling invalid input – outputting similar messages.

Syntax: ( condition ? trueExp : falseExp )

If condition is true, trueExp is used in the expression. If condition is false, falseExp is used in the expression.

Page 32: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Equivalent Code

The following statement stores the absolute value of the integer a into the integer absValue.

int absValue = ( a > 0 ? a : -a ); The equivalent statements using if/else are: int absValue;

if ( a > 0 )

absValue = a;

else

absValue = -a;

Page 33: CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1

Study Guide

• Chapter 5 – Sections 5.9, 5.10, 5.11– Study API for StringTokenizer (not covered in

text)

33