staple
here
(-‐2
if
not
stapled
or
double
sided)
over
Name: ________________________________ ID: _________________________
Ling 3 Fall 2016 Homework 3
1.You may recognize these problems from Homework 2. For each, write a phonological
rule of the type discussed in class today (/ / à [ ]). Show your work. (40 points)
A. Consider the distribution of [s] and [t] in these data from Tongan.
[tauhi] to take care [to] sugar cane [totonu] correct
[motomoto] unripe [sisi] garland [fesi] to break
[pasi] to clap [misi] to dream [motu] island
[sino] body [fata] shelf [mo] and
Write the phonological rule:
B. Consider the distribution of the [x] and [ç] in these data from German.
[axt] eight [ɪç] I [bux] book
[ɛçt] real [laxəәn] to laugh [lɔx] hole
[hoox] high [lɛçʌln] to smile [raɪçəәn] to reach
Write the phonological rule:
2. For each word in (a) through (e) below, identify its root and list the number of bound
morphemes it contains. [30 points]
root # bound morphemes
a reduplication
b immortalize
c demotivater
d detangling
e sarcastically
f immortalize
3. For each word in (a) through (f) below, identify its root, the syntactic category of the
root, and the syntactic category of the entire derived word. [30 points]
root root's category word’s category
a defenders
b unkindly
c unmovable
d nationalization
e demoralize
f darkening
Course/.DS_Store
__MACOSX/Course/._.DS_Store
Course/assert-except-DLV01.pdf
Review of pre- and post-condi2ons
public sta2c double getAverage(ArrayList<Integer> numbers) {
double sum = 0;
for (int n:numbers) {
sum += n;
}
return sum/numbers.size();
}
Consider the method getAverage shown below:
• What would a sensible set of preconditions be?
• What would be a good postcondition?
• Why might it not be a sensible idea to return an “error value” such as
-1 if the preconditions are not met?
• Why might it not be a sensible idea to write a message to the standard
error if the preconditions are not met?
1
Handling precondi2ons
• If the precondi2ons of our getAverage
method are not met then
– Returning -1 is probably not a good idea because you could have a list of
integers whose average genuinely was -1
– Wri2ng an error message to the standard error probably isn’t a good idea
either. We don’t know the context in which this method is called, so we don’t
know where the standard error actually gets wriRen to, or whether anyone
reads it.
• The only sensible things we can do are
– Stop the program – it is wrong!
– Throw an excep2on
2
asser2ons
• An asser2on is a statement that something should be true at a par2cular
point in a program.
• “I assert …”
...
2. work. (40 points)
A. Consider the distribution of [s] and [t] in these data from
Tongan.
[tauhi] to take care [to] sugar cane [totonu] correct
[motomoto] unripe [sisi] garland [fesi] to break
[pasi] to clap [misi] to dream [motu] island
[sino] body [fata] shelf [mo] and
Write the phonological rule:
B. Consider the distribution of the [x] and [ç] in these data from
German.
[axt] eight [ɪç] I [bux] book
[ɛçt] real [laxəən] to laugh [lɔx] hole
[hoox] high [lɛçʌln] to smile [raɪçəən] to reach
3. Write the phonological rule:
2. For each word in (a) through (e) below, identify its root and
list the number of bound
morphemes it contains. [30 points]
root # bound morphemes
a reduplication
b immortalize
c demotivater
d detangling
e sarcastically
f immortalize
4. 3. For each word in (a) through (f) below, identify its root, the
syntactic category of the
root, and the syntactic category of the entire derived word. [30
points]
root root's category word’s category
a defenders
b unkindly
c unmovable
d nationalization
e demoralize
f darkening
Course/.DS_Store
__MACOSX/Course/._.DS_Store
Course/assert-except-DLV01.pdf
5. Review of pre- and post-condi2ons
public sta2cdouble getAverage(ArrayList<Integer>
numbers) {
double sum = 0;
for (int n:numbers)
{
sum += n;
}
return
sum/numbers.size();
}
Consider the method getAverage shown below:
• What would a sensible set of preconditions be?
• What would be a good postcondition?
• Why might it not be a sensible idea to return an “error value”
such as
-1 if the preconditions are not met?
• Why might it not be a sensible idea to write a message to the
standard
error if the preconditions are not met?
1
Handling precondi2ons
• If the precondi2ons of our getAverage
6. method are not met then
– Returning -1 is probably not a good idea because
you could have a list of
integers whose average genuinely was -1
– Wri2ng an error message to the standard error
probably isn’t a good idea
either. We don’t know the context in which
this method is called, so we don’t
know where the standard error actually gets wriRen
to, or whether anyone
reads it.
• The only sensible things we can do are
– Stop the program – it is wrong!
– Throw an excep2on
2
asser2ons
• Anasser2on is a statement that somethingshould be
true at a par2cular
pointin a program.
• “I assert …”
public sta2cdouble getAverage(ArrayList<Integer>
numbers) {
assert numbers !=
null : "List is null”;
7. assert
numbers.size() > 0: "List is empty";
double sum = 0;
for (int n:
numbers) {
sum += n;
}
return
sum/numbers.size();
}
A condition to
check
Text of an
message to be
emitted if the
condition is false
3
Form of asser2on in Java
assert boolExp;
assert boolExpr: message;
where
boolExp is a Boolean expression and
message is a string.
8. if (boolExpr) ; // do nothing – all is
well
else
quit program and print the message
4
Uses of asser2ons
Documen2ng programs – sta2ng
what you can assume
or state confidently (assert):
i = 0;
while (i != N && a[i] != x)
i++;
assert i == N || a[i] == x; // this
really ought to be true!
Checking possibly faulty assump2ons
such as pre-condi2on of pop that
stackmust not be empty
5
9. Design by Contract™
With Design by Contract™ we don’t check
precondi2ons: it’s the responsibility of the client
to ensure them.
Example:
int daysEarlier(int y1, int m1, int d1, int y2, int
m2, int d2)
// return number of days by which
// date y1-m1-d1 is earlier (< 0 means
later) than date y2-m2-d2
6
DaysEarlier: ‘defensive’ version
int daysEarlier(int y1, int m1, int d1, int y2, int
m2, int d2)
// returns number of days by which
// y1-m1-d1 is earlier (< 0 means
later) than y2-m2-d2
// or -999 if either or both not a
validdate
days = DaysEarlier(2013, 06, 11, 1943,
06, 31);
if (days == -999)
System.out.println("One or both datesnot valid")
else System.out.println("days earlier is " +
days);
Outputs ‘One or both datesnot valid’! Why?
10. 7
Problem
days = DaysEarlier(2013, 10, 15, 2011, 01, 20);
if (days == -999) System.out.println(" One or
both datesnot valid")
else System.out.println(" days earlier is " +
days);
Says ‘One or both datesnot valid’! Why?
True story: Tookthreeweeks to solve!
8
This formalised as …
int daysEarlier(int y1, int m1, int d1, int y2, int
m2, int d2) {
// precondiJon
assert isDate(y1, m1, d1) && isDate(y2,
m2, d2) ;
…
// postcondiJon
// ensure result is number of days by which
// y1-m1-d1 is earlier (< 0 means later)
than y2-m2-d2
9
11. Switching on asser2on
checking in netbeans
To enable asser2on-checking in NetBeans
1. Right click on your project in the Projects tab
2. Select “Proper2es” and then “Run”
3. Type “-ea” or “-enableasser2ons” into the
“VMOp2ons” text box.
10
Switching on asser2on
checking in netbeans
11
Asser2on handling
• By default Java simply ignores asser2ons. This
means that they don’t slow down execu2on of
your code if you don’t want them checked.
• However if you specify the –ea op2on when
you
run your program, then the condi2ons associated
with asser2ons are checked. If they are not true
then an AsserJonError is thrown, a message
associatedwith the assert statement is emiRed
and the program stops.
12. • Asser.ons are for highligh.ng erroneous
programs.
12
ARempt exercises 1 to 10
13
Excep2ons are for things you
can’tforesee
Examples:
• when trying to open a file and read from it,
file by that name
might not exist, theremight not be suitable
data in the file.
• when typing a value at the keyboard the
user might type ill-
formed values, for example: integer wanted, other
characters
supplied.
14
What is an excep2on?
• Anexcep2on is an object that
13. describes a problem that has
occurred.
• Its getMessage method returns a
descrip2on of the problem.
• There are many different kinds of
excep2on. We have only shown a
few of them on this slide.
Throwable
getMessage()
printStackTrace()
Excep.on
Run.meExcep.on
IllegalArgumentExcep.on
IOExcep.on
FileNotFoundExcep.on NullPointerExcep.on
15
Checked and unchecked
excep2ons
IllegalArgumentExcepJon, like all subclasses
of RunJmeExcepJon is an unchecked
excep2on.
It is used to indicate that an argument
14. (parameter) has an unacceptable value
(violates a precondi2ons).
All otherexcep2ons are checked. A method
that can generate a checked excep2on must
either catch it, or explicitly declare that it
throws it.
Throwable
getMessage()
printStackTrace()
Excep.on
Run.meExcep.on
IllegalArgumentExcep.on
IOExcep.on
FileNotFoundExcep.on 16
try … catch example
try {
System.out.println("How old are you?");
int age= in.nextInt();
System.out.println("next year you'll be " +
(age + 1));
} catch (InputMismatchExcep2on excep2on){
System.out.println("input not well formed");
}
Note: { … } needed axer try and catch
15. even if only one statement.
17
Specifying that your method throws an excep2on
[accessSpecifier] returnType methodName
"(" (parameterType parameterName)* ")"
"throws" Excep2onClass Excep2onClass*
Example:
public void read(BufferedReader in)
throws IOExcep2on
18
Checked excep2ons
public sta2cvoid writeArray(ArrayList<Integer>
nums) {
PrintWriter out =
new PrintWriter(new FileWriter("OutFile.txt"));
for (int num :
nums) {
out.println(num);
}
out.close();
} This code will not compile because
the
16. FileWriter constructor can throw an
IOException, which is checked.
We must either catch this exception, or
explicitly declare that the method throws it.
19
Solu2on 1
Catch the excep2on
public sta2cvoid writeArray(ArrayList<Integer>
nums) {
try {
PrintWriter out = new PrintWriter(new
FileWriter("OutFile.txt"));
for (int num : nums) {
out.println(num);
}
out.close();
} catch
(IOExcep2on ex) {
System.out.println("Error opening file");
}
}
20
17. Solu2on 2
add a “throws” clause
public sta2cvoid writeArray(ArrayList<Integer>
nums) throws IOExcep2on {
PrintWriter out =
new PrintWriter(new FileWriter("OutFile.txt"));
for (int num :
nums) {
out.println(num);
}
out.close();
}
The compiler will be happy with this, because we have
acknowledged that the exception can be thrown. If there is
an exception handler further down the call stack then it
can be caught.
Note that the word is “throws” not “throw”
Question: Which solution is better?
21
Which solu2on is beRer
public sta2cvoid writeArray(ArrayList<Integer>
nums) {
try {
PrintWriter out = new PrintWriter(new
18. FileWriter("OutFile.txt"));
for (int num : nums) {
out.println(num);
}
out.close();
} catch
(IOExcep2on ex) {
System.out.println("Error opening file");
}
}
This solution assumes that the method is being called in a
context in
which we can write a message to standard output and be
confident
that someone will see it.
We can’t guarantee that this is true, so it is probably better to
throw
the exception and allow it to be caught by a handler that can
deal
with it more sensibly. 22
Throw early, catch late
• In general, a method should not catch an
excep2on unless you can guarantee that it will
be able to handle the excep2on in a sensible
way.
19. • If you cannot do this then it is beRer to
allow
the excep2on to be thrown.
23
Crea2ng your own excep2on class
You define a new class of excep2on by extending
someexcep2on class:
Example:
public class InsufficientFundsExcep2on extends
RunTimeExcep2on {
public InsufficientFundsExcep2on() { }
public InsufficientFundsExcep2on(String
message) {
super(message);
}
}
When the excep2on is caught its message string
can be retrieved using the
getMessage method.
24
Usage: throw
void withdraw(int amount) {
if (amount > balance) {
throw new InsufficientFundsExcep2on(
20. "withdrawal of " + amount +
" exceeds balance of " + balance);
else
balance-= amount;
}
25
Shame on you!
try {
withdraw(amount);
}
catch (InsufficientFundsExcep2on ex) {
System.out.println(ex.getMessage());
System.out.println("Shame on you for even
asking! ");
}
26
And finally…
public sta2cvoid writeArray (ArrayList<Integer>
nums) throws IOExcep2on {
PrintWriter out =
null;
try {
out = new PrintWriter(new
FileWriter("OutFile.txt"));
for (int num : nums) {
21. out.println(num);
}
} finally {
if
(out != null) {
out.close();
}
}
}
The finally block is executed if any exception is
thrown within the try block.
After the finally clause has been executed the
exception will be thrown. Note that we have not
caught the exception.
We still need the throws clause, because the
method can still throw an IOException
27
Try blocks with both catch and
finally blocks
public sta2cvoid writeArray5(ArrayList<Integer>
nums) {
PrintWriter out =
null;
try {
22. out = new PrintWriter(new
FileWriter("OutFile.txt"));
for (int num : nums) {
out.println(num);
}
} catch
(IOExcep2on ex) {
System.out.println("Error opening file");
} finally {
if
(out != null) {
out.close();
}
}
}
The finally block is executed if any exception is
thrown within the try block.
If an IOException was generated in the try block
then we would execute both the catch block, and
the finally block.
We no longer need the throws clause, because
the method catches the IOException
28
23. Try blocks with both catch and
finally blocks
• Although Java allows you to add both a catch
block and a finally block to the same try
block,
that does not mean it is a sensible thingto
do.
• The circumstances in which a finally block
would be useful are oxen different to those in
which a catch block would be sensible.
Furthermore code with both blocks can be
difficult to understand.
29
Summary
• Asser2ons are for dealing with broken pre- or
postcondi2ons or for asser2ng things that
really must be true (or else the program is
wrong).
• Excep2ons are for, such as invalid input,
broken network links. things that cannot be
foreseen
30
39. Week 5/9.png
__MACOSX/Week 5/._9.png
Tennis Score Board
This coursework is only 40% of your module mark. You will
write a GUI that can be
used to keep track of the score during a lawn tennis match at
Wimbledon. You will be
using MVC (Model View Controller) so you will submit the
Model first for 25% of
the module mark and then the View and Controller together for
15% of the module
mark.
This coursework will assess the following learning outcomes.
• Create a software artifact by applying the methodologies of
advanced object-
oriented programming to a requirements speciation
• Select and apply a design pattern from one of the major design
patterns to
solve a given problem
• Consult on-line code libraries to find the classes and methods
most appropriate
for solving a particular problem
• Create appropriate documentation that clearly communicates
the intend
behavior of a program
40. Description of the GUI
As you can see, the GUI is composed of two buttons, to be
pressed each time a player
wins a point, plus the scoreboard itself, which is divided into
three portions. The
central portion records the names of the two players. Each
match is played as the best
of five sets, so it continues until one player has won three. The
left portion, initially
blank, shows the results of the previous sets.
Each set is made up of a series of games, and each of these is
made up of a series of
points. The right portion shows the number of sets won and the
state of the current
set. You will need to implement both tie-breaks and deuce-
advantage play.
(http://en.wikipedia.org/wiki/Tennis_score has full details of
the scoring system.)
Part 1
Marking Scheme for Model
10% Model, implementing, for the highest marks, all the
required functionality with
an interface designed to be convenient for the Controller, View
and JUnit class to use
with no superfluous public methods. It should have no
references to those two classes
and contain no GUI code. It should be programmed according to
the principles of
good object-orientation; such as encapsulation, inheritance and
polymorphism. It will
41. likely have many classes and therefore it should have an
explanatory class diagram.
5% Specification of Model in JML or Spec# or asserts,
including invariants for the
class as well as pre and post conditions for each method. This
will be marked
according to how many of the relevant conditions are included
and the correctness of
the JML / Spec# / asserts. Partial credit will be available for
describing them in
English. Some statements may be un-provable due to the
limitations of JML / Spec#
even when specified correctly. In such cases, there will be no
negative affect on your
marks.
10% Unit testing of the Model in JUnit. There should be three
tests, significantly
different from each other. You should explain in comments the
particular situation
you are testing for. You should use write (and then call)
methods for the Model that
set it into the state desired for the test. It should be easy to see
what state the Model is
being set to by reading the code for the unit tests.
Part 2
Marking Scheme for View and Controller
5% Controller, which must forward only valid requests to the
Model, querying the
Model if necessary to and out if the request is valid, and must
42. also enable / disable
buttons as appropriate. In particular, when the match has
finished, it should disable
the buttons and cause the View to change all the yellow writing
to grey, except for the
winner's name, which will be in red. It must have no GUI code,
though it may send
messages to the View. It will be marked with respect to these
requirements.
5% View, which will be multiplied by a number between 0 and
1, indicating the code
quality/commenting/formatting as described above for the
Model. For example, there
should be no “magic numbers” i.e. all calculations of (x,y)-
coordinates should be
based on predefined constants.
5% Another copy of View, translated to the JavaFX framework,
instead of Swing. It
will also be scaled in the same way.