home—info—lects—labs—exams—hws
tutor/PIs—java.lang docs—java.util docs
lect04a
Nesting if-else
Let's write a function determining whether somebody's track time
would qualify for the olympics, in the 100m dash.
Follow the steps of
the design recipe.
-
Data analysis — What are the pieces of information
at hand, for this problem, and
which data types should be used to represent them in the program?
(E.g., int, String,
boolean, ...?)
-
Examples of the data.
Make a bunch of example instances.
-
Signature — for each method (function),
specify its name, what input parameters it needs (name and type),
and what type of information it will return.
- Comments (written in
javadoc).
Describe what each parameter means
(for example “the price of the item, in dollars”,
or “the number of students officially enrolled in the course”)
as well as the meaning of the return value.
-
Complete the stub function, and compile.
Note that you still haven't yet written any code which
computes a solution.
-
Test cases:
Write a test driver with 2-3 test cases (or more, as appropriate).
- A test case includes input(s), and the
expected output.
- Include at least one test with a degenerate input
(if appropriate). For numbers, consider 0, 1.
For Strings, consider the empty string.
- Include at least one typical-use case.
- Consider whether fractional or negative numbers are
possible inputs. Either include a test case with them,
or make sure your comments state clearly they are not allowed.
-
The body of the function.
This is the only non-automatic part of the process.
Reflect on the test cases you worked through by hand:
how did you get from the input to the output?
What is the general case?
Things to help you on your way:
- Remind yourself of
exactly what pieces of info you have, to calculate your answer from.
- What are the types of each of these data?
What pertinent methods can you call, on data of that type?
-
Test — run the test cases you already wrote down
from step 2.
Does your program give the results you expect?
-
Refactor — review and (as necessary) rewrite your
code. Does it obey the The Laws of Programming?
Solution (scroll down to the function)
We'll now evolve this program:
-
Let's represent gender by a boolean, not a char.
-
Let's have our return statement use the result of > directly.
AND,OR
Finally:
We'll modify qualifies100m so that
it just has a single return statement (!).
This is not required, but some people prefer this version.
(Note that if your function doesn't return a boolean,
you won't be able to concentrate the code this much.)
home—info—lects—labs—exams—hws
tutor/PIs—java.lang docs—java.util docs