Post on 21-Dec-2015
OOP in JavaOOP in JavaRepetitionRepetition Constants Constants SelectionSelectionExceptionException
by Kasper B. Graversen
(c) Kasper B. Graversen 2
RepetitionRepetition• 3 different kinds
– for– while– do-while
• Each can be transformed to any other
• Enables stop-condition to be placed before or after a repetition
(c) Kasper B. Graversen 3
RepetitionRepetition
• The for() construction we saw 2 weeks ago.
initial
statements
next
conditionfalse
true
(c) Kasper B. Graversen 4
RepetitionRepetition
• Formallywhile(condition){ code… }
• Unlike for we have to do the “next” code in the statements
condition
statements
false
true
(c) Kasper B. Graversen 5
RepetitionRepetition• Formallydo { code… } while(condition);
• Unlike for we have to do the “next” code in the code
• Unlike for/while we do condition after the first loop
condition
statements
falsetrue
(c) Kasper B. Graversen 6
RepetitionRepetition• When to use what?
I prefer– for when a fixed number of iterations are
to be performed i.e. do something X times– while when doing something an unknown
number of times, I.e. reading information from a file
– do-while when I need code to be performed before a condition can be checked.
(c) Kasper B. Graversen 7
RepetitionRepetition• We can stop loops, ie. when
looking for a person in a fileStudent stud = null;do{ String name = in.readString(); if(name.equals(“hans”)) { stud = new Student(name);
break; }}while(stud == null);
(c) Kasper B. Graversen 8
RepetitionRepetition• Given the formula
cn = c0 * (1+i/100)n
do 1+i/100 n times
int interest(int i, int c0, int n)
{
int accumulated = 0;
for(int j = 0; j < n; j++)
accumulated *= 1+i/100;
int cn = c0 * accumulated;
return cn;
}
OOP in JavaOOP in JavaRepetitionRepetition Constants Constants SelectionSelectionExceptionException
by Kasper B. Graversen
(c) Kasper B. Graversen 10
ConstantsConstants• Constants are values which never
change value– pi = 3.1415926535– cards = 52
• Use the final keyword to ensures the values stay unmodified. Use only CAPITALS in the nameclass Deck{ public static final int DECSIZE = 52;}
(c) Kasper B. Graversen 11
ConstantsConstants• Heavily used variable input which at
compile time can be checkedclass Student{ Student(String name,String haircolor) { if(haircolor.equals(…)) else if(…) … else …Wrong haircolor… }}
(c) Kasper B. Graversen 12
ConstantsConstants
Students are then created with
class Student{ public static final int REDHAIR = 0; public static final int BLONDHAIR = 1; public static final int BLUEHAIR = 2; Student(String name, int haircolor) { if(haircolor == REDHAIR) … }}
Student s = new Student(“Leo”,Student.REDHAIR);Spelling errors such as REDHAR are checked (since there are no variables of such name)Student s = new Student(“Leo”,223);is not checked at compile time
(c) Kasper B. Graversen 13
ConstantsConstants• Its also an easy way to tell the user of
the object which hair colors are available (particularly in Javadoc)
• Using constants, however, do not prevent you from typing the wrong haircolor (you wanted a redhead but typed blond :-)
(c) Kasper B. Graversen 14
ConstantsConstants• Heavily used for arguments which can
be checked at compile timeclass Student{ Student(String name,String haircolor) { if(haircolor.equals(…)) else if(…) … else …Wrong haircolor… }}
(c) Kasper B. Graversen 15
Static & constantsStatic & constants• static means “exist outside of
objects”. No matter how many objects there will be only one constant (ie. 2000 Deck objects but only one DECKSIZE with value 52)
• static allows use of constants before any objects of the class has been instantiated.
• All constants should be static
(c) Kasper B. Graversen 16
StaticStatic • Use static on methods if you find
the course easy• Use static on methods if they do
not require an object to work in (ie. Math.max(int,int))
• static is useful but not used often (check the javadocs)
OOP in JavaOOP in JavaRepetitionRepetitionConstantsConstants SelectionSelectionExceptionException
by Kasper B. Graversen
(c) Kasper B. Graversen 18
SelectionSelection• switch-case is an efficient and
easy way to do selectionsif(i == 0) …(a)… else if(i == 1) …(b)…else if(i == 2 || i == 3) …(c)…else …(d)…
switch(i){ case 0: …(a)… break; case 1: …(b)… break;
case 2: case 3: …(c)… break; default: …(d)… break;}
(c) Kasper B. Graversen 19
SelectionSelection• switch Applies only to simple type
integer values int,long,char• Not efficient with intervals• Can not handle && used in if• The examples below show cases where
a “translated” to switch-case is impossible.
LimitationsLimitations
if(i == 2 && year == 2001)if(age > 25)if(surname.equals(“Hans”) || lastname.equals(“Nielsen”));
OOP in JavaOOP in JavaRepetitionRepetitionConstantsConstants SelectionSelectionExceptionException
by Kasper B. Graversen
(c) Kasper B. Graversen 21
ExceptionsExceptions“V-shaped” or “chunked” styleof programming
lack of...lack of...
if(… != -1){ …D… if(… != -1) { …E… if(… != -1) {…F… } else {(ErrorA);} } else {(ErrorB);}}else{(ErrorC);}
if(… == -1){ (ErrorA) return;}…D… if(… == -1){ (ErrorB) return;}…E… if(… == -1){ (ErrorC) return;}…F…
(c) Kasper B. Graversen 22
ExceptionsExceptions• Using exceptions separates logic and
error handling• Result: two clean code blocks.• Methods have two choices
– Handle the exception ourselves– Throw it back to the one who called the
method
• Choice depends on the situation. Can the error be handled locally then do it.
(c) Kasper B. Graversen 23
ExceptionsExceptionsclass CardIndex{ … try { setupWindow(); loadPersons(); manipulate(); savePersons(); } catch(SetupException e) { … } catch(LoadException e){ … } catch(SaveException e){ … } catch(Exception e){ … }}
(c) Kasper B. Graversen 24
ExceptionsExceptionstry{ setupWindow(); try { loadPersons(); } catch(IOException e){ … } manipulate(); try { savePersons(); } catch(IOException e){ … }}catch(SetupException e) { … }catch(Exception e){ … }
Sharing exceptionsSharing exceptions
(c) Kasper B. Graversen 25
ExceptionsExceptions
private void setupWindow() throws SetupException{ … throw new SetupException();}
Throwing exceptionsThrowing exceptions
•Throw them explicitly
•Use classes which throws
private void loadPersons() throws IOException{ Stream in = new Stream(“file.txt”); in.read…()}
(c) Kasper B. Graversen 26
ExceptionsExceptions
• Throwing an exception in a constructor terminates the construction of the object
Student s = new Student()
if(s == null)
System.out.println(“uhohh!”);
In constructorsIn constructors
(c) Kasper B. Graversen 27
ExceptionsExceptions
• Make a new class extending class Exception
Defining new onesDefining new ones
class SetupException extends Exception{ public SetupException(String s) { super(s);}}
(c) Kasper B. Graversen 28
Case studyCase study• A program is needed for having an
electronic auction on articles sold by people using the public transportation.
• At central station a computer is setup.• People should be able to see the article,
the current bid and be able to bid themselves
• Since central station closes at night, the program must be able to handle this
(c) Kasper B. Graversen 29
Case studyCase study• A program is needed for having an
electronic auction on articles sold by people using the public transportation.
• At central station a computer is setup.• People should be able to see the article,
the current bid and be able to bid themselves
• Since central station closes at night, the program must be able to handle this
what’s what’s relevantrelevant
(c) Kasper B. Graversen 30
Case studyCase study• Implicit requirements
– New bids must be higher than the existing one
– A bidder must give information about him (in our simple case, a name)
– The program must be quick and easy to use
(c) Kasper B. Graversen 32
The codeThe codeimport java.io.*;import javagently.*;class Auction{ private String filename; // name of dat file private String article; // name of article to be sold private String seller; // name of seller private int bid; // highest bid so far private String bidmaker; // current buyer private Display window; public static void main(String[] args) { try { Auction auc = new Auction("auction.dat"); while(true) { auc.round(); } } catch(IOException e) { System.out.print("An error has occoured+ " +e.getMessage()); } }
(c) Kasper B. Graversen 33
public Auction(String filename) throws IOException { this.filename = filename; readDatFile(); setupWindow(); }
private void readDatFile() throws IOException { Stream in = new Stream(filename, Stream.READ); String header = in.readString(); if(!header.equals("auction1.0")) { in.close(); throw new IOException("Wrong dat file, header was \""+header+"\""); } article = in.readString(); seller = in.readString(); bid = in.readInt(); bidmaker = in.readString(); in.close(); }
(c) Kasper B. Graversen 34
The codeThe code private void setupWindow() { window = new Display("Auction v1.0"); window.println("Welcome to auction v1.0"); window.println("Today we are selling " + article); window.println("Owned by " + seller); window.prompt("newBidmaker", " "); window.prompt("newBid", bid+100); }
(c) Kasper B. Graversen 35
public void round() throws IOException { window.println("Highest bid so far: " + bid); window.println("Made by " + bidmaker); window.ready("Press ready when you have entered the fields"); String name = window.getString("newBidmaker"); int newbid = window.getInt("newBid"); if(name.length() > 2 && newbid > bid) { bid = newbid; bidmaker = name; // save to disc Stream out = new Stream(filename, Stream.WRITE); out.println("auction1.0"); // print the header out.println(article); out.println(seller); out.println(bid); out.println(bidmaker); out.close(); } }