Synopsis
More application architectures in this class as well as Imperative programming, another powerful idea, and basic If /Else decision making.
|
The ``Objective'' solution to the line of squares problem
class LineOfSquaresApp
{
static public void main (String args []
{
LineOfSquares los = new LineOfSquares ();
double p = los.perimeter ();
IO.println ( ``Perimeter is ``+ p);
}
class LineOfSquares
{
/ /instantiate variables (instances)
private int nrSquares; / /private inaccessible outside of this class
private double edgeLength;
/ /constructor method
public LineOfSquares ()
{
IO.print ( ``How many squares? ``);
nrSquares = IO.read_int ();
? IO.print ( ``Area of figure? ``);
double areaOfFigure = IO.read_double ();
double areaOfSquare = areaOfFigure /nrSquares;
edgeLength = Math.sqrt (areaOfSquare);
}
/ /perimeter method
public double perimeter ()
{
return edgeLength * eeCount ();
}
/ /eecount - should be private since method is not used outside of this class LineOfSquares
private int eeCount ()
{
return (nrSquares * 2) + 2;
}
}}
|
Lab discussion ensued - recap of last weeks lab and work on current programming challenge
Definition
IMPERATIVE PROGRAMMING is a style of programming which features
commands
.
Remark
Characteristics of the imperative style are...
- Binding commands (assignment statements)
- Conditional commands (selectors)
- Repetition commands
- IO commands
Program to read two integers and display the larger of the two
Method 1
int a = IO.read_int ();
int b = IO.read_int ();
|
conditional style (use brace on next line for class stuff)
if (a > b)
\ttline
IO.println (a); (/ /this is the THEN part)
}
else
{
IO.println (b); (/ /ELSE part)
}
|
Method 2
Program to read two integers and display the work ``Ok'' if they are not equal.
int a = IO.read_int ();
int b = IO.read_int ();
|
if (a! = b)
{
IO.println ( ``ok'');
}
|
Multiway if
Read one integer and display ``zero'', ``negative'', '' positive'' depending on the integer.
int a = IO.read_int ();
if (a > 0)
{
IO.println ( ``positive'');
}
else if (a < 0)
{
IO.println ( ``negative'');
}
else
{
IO.println ( ``Zero'');
}
|
Way (1) Nested ifs (AWFUL SOLUTION - DON'T DO IN ACTUAL CODE UNLESS YOU LIKE TO GET BAD GRADES AS A HOBBY! )
/ /read the integers
int a = IO.read_int ();
int b = IO.read_int ();
int c = IO.read_int ();
|
if (a < b)
{
if (a < c)
{
IO.println (a);
if (b < c)
{
IO.println (b);
IO.println (c);
}
else
{
IO.println (c);
IO.println (b);
}
|
Never nest if statements - rethink and recode to a better style - multiway ifs with abstraction.
Way 2 - multiway if with abstraction
if (less (a, b, c))
{
IO.println (a + ````+ b + ````+ c);
}
else if (less (a, c, b))
{
IO.println (a + ````+ c + ````+ b);
}
continues with another else if until all cases are accounted for
static private boolean less (int x, int y, int z)
{
if (x < y)
{
if (y < z)
{
return true;
}
}
return false;
}
|