Nov. 22, 2005
Grouping Data Elements Together
- We have learned that an
arbitrarily sophisticated algorithm can be implemented by grouping
together very simple structures (assignment, loop, decision, method
call).
- Yet, in looking at data
elements, we have dealt mostly with individual variables that contain
scalar values (integer, float) or simple objects (Student, Address).
- We need to round out our
experience by looking at how to group simple data elements together to
form arbitrarily sophisticated data structures.
- Just as a subprogram (method)
collects program statements into a single named entity, a composite
data structure collects data elements into a single named entity.
Arrays
A particular value in an array is
referenced using the array name followed by the index in brackets
For example, the expression
scores[2]
refers to the value 94 (the 3rd
value in the array)
That expression represents a place
to store a single integer and can be used wherever an integer variable
can be used
Arrays
For example, an array element can be
assigned a value, printed, or used in a calculation:
scores[2] = 89;
scores[first] = scores[first] + 2;
mean
= (scores[0] + scores[1])/2;
System.out.println ("Top = " + scores[5]);
Arrays
- The values held in an array
are called array elements
- An array stores multiple
values of the same type (the element type)
- The element type can be a
primitive type or an object reference
- Therefore, we can create an
array of integers, or an array of characters, or an array of String
objects, etc.
- In Java, the array itself is
an object
- Therefore the name of the
array is an object reference variable, and the array itself must be
instantiated
Declaring Arrays
- The scores array could be
declared as follows:
- int[] scores = new int[10];
- The type of the variable
scores is int[] (an array
of integers)
- Note that the type of the
array does not specify its size, but each object of that type has a
specific size
- The reference variable scores
is set to a new array object that can hold 10 integers
- See BasicArray.java (page 322)
Nov. 15-17
Writing Your Own Classes and Methods
- Sets of reusable classes which
provide generally usable methods are the basis for all modern software
development, regardless of language or operating system.
- There are a number of kinds of
methods.
- A public method is available
to any program that imports the class; a private method is available
only to other methods within the class. At this time we'll consider
only public ones.
- A static method is associated
with the class; a non-static method is associated with each object. At
this time we'll consider only static ones.
- A value-returning method is
one that returns a value to the calling program; a void method is one
that does not return a value. At this time we'll consider both
value-returning and void methods.
More on Classes and Methods
Let's look at classes which are instantiated to produce objects. What
are
some of the common characteristics of such classes and objects?
- An object has state (a set of data values, sometimes
called fields
or attributes) and behavior (a set of methods). The
methods
act on the data values, which changes the overall state.
- The data values are usually declared to be private, so
that a calling
program must call methods to modify them and can't modify them directly.
- The methods are usually declared to be public, so a
calling program
can use them. Sometimes there are also private methods; why would we
want
these?
Common kinds of methods
- Constructor: creates and returns object from a class.
Usually has
a list of parameters, and uses these to set the object's data values.
The
constructor's name is always that of the class; it has no return
statement.
- "Setter": usually has parameters, which it uses to modify
one or
more of an existing object's data values.
- "Getter": usually has no parameters; it just returns one
of the
object's data values.
- input: reads an objects data values from the keyboard or
from a
file.
- toString: collects (some of) an object's data values together
into a string,
suitable for displaying or writing to a file.
Aggregation
An aggregate object is an object that contains references to other
objects
For example, an Account object contains a reference to a String object
(the owner's name)
An aggregate object represents a has-a relationship
A bank account has a name
Likewise, a student may have one or more addresses
Sept. 15-20, 2005
Example: Average Age of Professors
Problem Specification
You're a very curious person. One thing you're curious about is the
ages of three of your professors. But how can you find out how old they
are? Some people are offended if you ask their age.
Luckily, the GW Undergraduate Bulletin has a list of (most of) the
professors in the back of the book. Each professor's listing gives
his/her degrees, showing the college or university and year of each
degree.
If we assume the typical student is 21 when (s)he earns a bachelors
degree, we can estimate a professor's age just by knowing the current
calendar year and that professor's graduation year.
You're also curious about the mean (average) age of the profs.
Analysis
To solve this problem, we must be given the current year, and the
graduation years of the three profs. The estimated age (to the nearest
year) of a prof can be computed from these values. The mean age will be
the sum of the ages divided by the number of profs (3).
Data Requirements and Formulas
Problem Inputs:
thisYear - the current calendar year, an integer
year - the graduation year of each prof in turn, an integer
Problem Outputs:
age1, age2, age3 - the ages of the three professors (integers)
meanAge - the mean age of the professors
Relevant Formulas
Estimated age = current year - graduation year + 21
Initial Algorithm
- Prompt the user and read in each professor's
graduation
year, then calculate and display that professor's estimated age.
- Prompt
the user and read in
the current year.
- Compute
the mean age.
- Display the mean age.
Algorithm Refinements
Step 2 can be refined:
2.1 Prompt the user and read in 1st
professor's graduation year, then
calculate and display that professor's estimated age.
2.2 Prompt the user and read in 2nd professor's graduation year, then
calculate and display that professor's estimated age.
2.3 Prompt the user and read in 3rd professor's graduation year, then
calculate and display that professor's estimated age.
Test Plan
Let's develop one right here!
Implementation
Start with the template - it's unnecessary to start with a blank page
mfeldman@hobbes.seas.gwu.edu:15:
cp
programs53/ProjectTemplate.java .
mfeldman@hobbes.seas.gwu.edu:16:
cat ProjectTemplate.java
//--------------------------------------------------------------
//| ProjectTemplate.java <--
change to your project filename
//| Use this as a basis for your
own programs
//| Author: <your name>,
The George Washington University
//| Last Modified: <date>
//--------------------------------------------------------------
import cs1.Keyboard;
public class ProjectTemplate
<-- change to your project name
{
public static void main
(String[] args)
{
// put your code here
}
}
Declare the variables and copy the main algorithm steps
as comments: framework file.
//--------------------------------------------------------------
//| MeanAge.java
//| Finds mean estimated age of
three professors
//| Author: M.B. Feldman, The
George Washington University
//| Last Modified: September 9,
2002
//--------------------------------------------------------------
import cs1.Keyboard;
public class MeanAge
{
public static void main
(String[] args)
{
int thisYear;
// input - the current calendar year
int year; //
input - year of a prof's bachelors deg.
int age1; //
output - 1st prof's estimated age
int age2; //
output - 1st prof's estimated age
int age3; // output
- 1st prof's estimated age
int meanAge; //
output - mean of 3 ages
// Prompt the user
and read in the current calendar year
// Prompt the user
and read in 1st prof's degree year
// and compute and
display that prof's estimated age
// Prompt the user
and read in 2nd prof's degree year
// and compute and
display that prof's estimated age
// Prompt the user
and read in 3rd prof's degree year
// and compute and
display that prof's estimated age
// Compute the mean
age
// Display the mean
age
}
}
Compile the framework; fix any errors. Then fill in the
rest of the program statements.
See
MeanAge.java in
the program distribution.
Improved Algorithm
We can improve the algorithm a bit by realizing that we don't need 3
separate age variables. We can use one variable over and over, as long
as we accumulate the sum of the ages as we go along. We need a sum
variable; let's call it ageSum.
This gives a new refinement of Step 2:
2.1 Prompt the user and read in 1st professor's graduation year, then
calculate and display that professor's estimated age, and add it into
the running age sum.
2.2 Prompt the user and read in 2nd professor's graduation year, then
calculate and display that professor's estimated age, and add it into
the running age sum.
2.3 Prompt the user and read in 3rd professor's graduation year, then
calculate and display that professor's estimated age, and add it into
the running age sum.
See MeanAge2.java in
the program distribution.
Notes from Thursday, Sept. 8, 2005
What Does It Take to Be a
Good Software Developer?
Software developers are, above all,
systematic problem solvers
- a “logical mind”
- a willingness to approach problems methodically
- break problems up into sub-problems
- don’t panic at the size of a problem;
- it may seem overwhelming but it is
- within your grasp to solve it if
- you approach it methodically
The Software Development Method
1. Problem specification
2. Analysis
3. Design
4. Test plan
5. Implementation or coding
6. Testing
The Software Development Method
1. Problem specification: State the problem and gain
a clear understanding of what is required for its solution. This sounds
easy, but it can be the most critical part of problem solving. A good
problem solver must be able to recognize and define the problem
precisely. If the problem is not totally defined, you must study the
problem carefully, eliminating the aspects that are unimportant and
zeroing in on the root problem.
2. Analysis: Identify problem inputs, desired
outputs, and any additional requirements of or constraints on the
solution. Identify what information is supplied as problem data and
what results should be computed and displayed. Also, determine the
required form and units in which the results should be displayed (for
example, as a table with specific column headings).
3. Design: Develop a list of steps (called an
algorithm) to solve the problem and verify that the algorithm solves
the problem as intended. Writing the algorithm is often the most
difficult part of the problem-solving process. Once you have the
algorithm, you should verify that it is correct before proceeding
further.
4. Test plan: Develop a strategy for proving to
yourself and to others that your algorithm will get the proper results.
It is highly advisable to write a plan for testing the program you will
write, even before you have written it. Which test cases will you
choose? What are the special cases that must be tested? Pretend you are
a potential purchaser of the program and ask, “Which tests would I
require to be convinced that this program behaves as advertised?”
5. Implementation or coding: Implement the algorithm
as a program. This requires knowledge of a particular programming
language. Each algorithm step must be converted into a statement in
that programming language.
6. Testing: Run the completed program, testing it
with the test cases specified in the test plan.
Example: Average Speed on Trip
Problem Specification
Next week, you're driving to Long Island to visit your family. When you
drive, you'd like to know what your average end-to-end speed, in miles
per hour, was for the trip.
You're not very good at arithmetic. Luckily, you'll have your trusty
laptop with you, so you can develop a little program that will compute
your average speed from the distance you've driven and the number of
hours the trip took.
Unfortunately, your laptop is a bit lame-brained, so it's able to
caculate only with "whole numbers" (integers).
Analysis
To solve this problem, we must be given the number of miles (to the
nearest mile) and the number of hours (to the nearest hour). The
average speed (to the nearest MPH) will be the quotient of the number
of miles divided by the number of hours.
Data Requirements and Formulas
Problem Inputs:
miles - the number of miles, an integer
hours - the number of hours, an integer
Problem Outputs:
mph - the average speed, to the nearest integer value
Relevant Formulas
mph = miles ÷ hours
Initial Algorithm
- Prompt the user and read in the number of miles.
- Prompt the user and read in the number of hours.
- Compute the average speed.
- Display the average speed.
Algorithm Refinements
This is a very simple algorithm and needs no refinements.
Test Plan
Let's develop one right here!
Implementation
Start with the template - it's unnecessary to start with a blank page
mfeldman@hobbes.seas.gwu.edu:15:
cp programs53/ProjectTemplate.java .
mfeldman@hobbes.seas.gwu.edu:16: cat ProjectTemplate.java
//--------------------------------------------------------------
//| ProjectTemplate.java <-- change to your project filename
//| Use this as a basis for your own programs
//| Author: <your name>, The George Washington University
//| Last Modified: <date>
//--------------------------------------------------------------
import cs1.Keyboard;
public class ProjectTemplate <-- change to your project name
{
public static void main (String[] args)
{
// put your code here
}
}
Declare the variables and copy the main
algorithm steps as comments. This is called a
framework file.
//--------------------------------------------------------------
//| AverageSpeed.java
//| Finds average speed on a trip.java
//| Author: M.B. Feldman, The George Washington University
//| Last Modified: September 5, 2002
//--------------------------------------------------------------
import cs1.Keyboard;
public class AverageSpeed
{
public static void main (String[] args)
{
int
miles; //
input - number of miles driven
int
hours; //
input - number of hours driven
int
mph;
// output - miles per hour
// Prompt the user and read in the number of miles
// Prompt the user and read in the number of hours
// Compute the average speed
// Display the average speed
}
}
Compile the framework; fix any errors. Then
fill in the rest of the program statements.
//--------------------------------------------------------------
//| AverageSpeed.java
//| Finds average speed on a trip.java
//| Author: M.B. Feldman, The George Washington University
//| Last Modified: September 5, 2002
//--------------------------------------------------------------
import cs1.Keyboard;
public class AverageSpeed
{
public static void main (String[] args)
{
int
miles; //
input - number of miles driven
int
hours; //
input - number of hours driven
int
mph;
// output - miles per hour
// Prompt the user and read in the number of miles
System.out.print
("How many miles did you drive (to the
nearest mile)? ");
miles = Keyboard.readInt();
// Prompt the user and read in the number of hours
System.out.print
("How many hours did you drive (to the
nearest hour)? ");
hours = Keyboard.readInt();
// Compute the average speed
mph = miles / hours;
// Display the average speed
System.out.print ("Your average speed
was ");
System.out.println (mph + " miles per hour.");
}
}