Extending the Robot Programming Language

Programming Process


Programming in Java is an exercise in using pre-defined
classes and writing new classes to fill in the gaps
A procedure for determining the relevant objects for
design and application:
1.
2.
3.
4.
5.
Determine primary objects by examining the nouns of the
problem statement
Decide upon the primary behavior of the classes
corresponding to these objects
Define the interface
Introduce instance variables to maintain state
Implement the method bodies
Designing Classes: an overview

Statement of problem
–
–

Find the primary objects
–
–

–
–

Produce basic set of required methods
Multiple objects, work one object at a time
Determine the interface
–

Key elements of the model
Collect all the nouns in the problem statement
Demonstrate the desired behavior of the objects
–

Describes the object or system to be modeled
Sketch a sample scenario illustrating the solution
Prototype each method; arguments and return types
Write sample code to see how methods are invoked
Define necessary instance variables
Implement the methods
Numeric processing(page 64-70)


Method implementation requires a wide variety of tools,
including the ability to process numbers
Java defines primitive data types including numeric types
–
Integer and floating point types

–
Not classes or objects, utilize underlying hardware


–

int, short, byte, long, float, double
Cannot receive messages; have no associated methods
There are associated classes with these types, to be looked at
later
Form expressions as operands of operators
Static methods
–
–
Written to supplement the basic arithmetic operations
Can accept primitive data type as an argument and return
value
The int data type

Built-in data type
–

Models the behavior of integers (whole numbers)
Data type provides basic arithmetic operations
–
–
+ (addition), - (subtraction), * (multiplication), /
(division)
Used to construct standard arithmetic expressions
x + y * z
–
Integers can be printed by the overloaded print and
println methods of the PrintStream class
System.out.println(total / count);
Working with int

Declarations are like reference variables
int count;
int number, size;
Have no methods or instance variables
– An integer value is the only thing that can be associated with
a variable of type int

–
The value may be assigned when the variable is declared
int count = 0;
–
Or through an assignment statement
total = cost * count;
No constructors, and no new instruction
Basic arithmetic
Operation
Addition
Subtraction
Multiplication
Division
Remainder
Operator
Example
Result
+
-
7 + 5
12
7 – 5
2
*
/
%
7 * 5
35
7 / 5
1
7 % 5
2
• Integer division results in integer results
- the results are whole numbers
Constants & literals

Constants
–
–
There are some values that will not change over the life of
the program, they have a constant value
Constants are declared using the form
static final type identifier
–
= value
Example:
static final int numStudents = 20;
 final : constants value is final, it will never change
 static : constant belongs to the class, not an instance of the
class

Literals
–
In the expression
int total
–
= 2 * cost;
The 2 is a literal because it is a literal representation of its
value, (which can never be changed)
Precedence

What is the result of this expression?
2 + 6 / 8
– 1
– 2

An ambiguous expression, unless precedence rules are
available to resolve ambiguities
–
–
–
Multiplication and division have higher precedence than
addition subtraction
If more than one operator of the same precedence, the
expression is evaluated from the left to the right
Parentheses can be used to clarify ambiguity or to overwrite
precedence rules
Compound Assignment Operators

What does the following mean? Is it nonsense?
total = total * 2
count = count + 1

// doubling total
// incrementing count
These kind of operations happen so often that there are
special operator shorthand for them
Operation
Standard
Shortcut
Addition
total = total + 2
total += 2
Subtraction
total = total – 2
total -= 2
Multiplication
total = total * 2
total *= 2
Division
total = total / 2
total /= 2
Remainder
total = total % 2
total %= 2
Increment
count = count + 1
count++
or ++count
Decrement
count = count - 1
count--
or --count
String objects and the + operator


String concatenation is a common operation in
Java
Therefore the + operator is overloaded for
concatenating string objects
string1 + string2;
is Java shorthand for
string1.concat(string2)
int input

To read an int value into an int variable (from keyboard
or file)
–
–
Read the line from the data file into a String object, using
readLine()
Convert the String value into the int value using the
static parseInt() method of the predefined class Integer
–
Example
String s = br.readLine();
int num = Integer.parseInt(s);
–
Or
int num = Integer.parseInt(br.readLine());
Other integer types

long
–
–
–
–

The int type models a range of integers from –2 billion to 2
billion
When we need a larger range of values we use the long
type, which models a range of integers from –8 quintillion to
8 quintillion
long is identical to ints in terms of values, operators, and
behaviors
However long literals have an L appended to them
long num = 4000000000L;
Should all integers be long?
–
–
ints require 32 bits of memory, longs 64 bits
Most computers today are 32 bit computers, and they cannot
carry out 64 bit arithmetic as efficiently
Mixed type arithmetic

int values may be assigned to long variables
–

No chance of information being lost
However, if we want to assign a long value to
an int, even if it is a legitimate int value
(range), we must cast the value as an int
long bigNum = 1000000;
int s =(int)bigNum;
Other integer types

Represent smaller range of integers, require
less memory
–
short

–
Byte


-32768 to 32767 (16 bits)
-128 to 127 (8 bits)
Mixed arithmetic rules follow the same pattern
set by long and int
–
If information might be lost as a result of an
assignment, an explicit cast is required
Numbers of Measurement:
Floating Point numbers


Numbers with fractional parts; precision is
always an issue
Two types that model floating point behavior
–
float

–
Models floating point numbers with approximately 7
digits of precision
double

Models floating point numbers with approximately 15
digits of precision
Using floating point numbers

Print() and println() are overloaded as with ints
–
Format for printing floats and doubles borrows from scientific
notation
3.4028235 X 1038

 3.4028235E38
Literals can be written using the scientific notation style
–
The decimal point, the fraction, the exponent may all be omitted
–
To distinguish float from double, float literals must have a trailing f
3.14159f
–
To distinguish double literals that look like int literals, they must
have a trailing d
98d
Using floating point numbers (2)

Declaring doubles and floats is similar to
declaring ints
double area, perimiter;
static final double pi = 3.14159;
double price = 1.99;

Operators for addition (+), subtraction (-), multiplication
(*), and division (/) works with floting point numbers
– You cannot find the remainder (%) of floating point division,
however

Shortcut assignment operators (+=, -+, *=, /=) work
–
Increment does not
Reading float and double

The book says there is no parseDouble() in the Double
class, and no parseFloat() in the Float class
–
–
–
–
–
However the API shows them both, and I believe that they
are now implemented
Reading a double or float value should be like reading an
int
Example
String s = br.readLine();
double value = Double.parseDouble(s);
Or
double num = Double.parseDouble(br.readLine());
If this doesn’t work we will use the style showed in the text
double num = Double.valueOf(br.readLine()).doubleValue();
Mixed type arithmetic

double to float follow the same pattern set by
long and int
–

If information might be lost as a result of an
assignment, an explicit cast is required
Mixing integer types and floating point types
–
–
–
Integers may be assigned to floating points
Floating point to integers requires a cast
Assigning a long to a float or double may result in
loss of precision
Mixed type expressions

What is the result of this expression?
–
–

int count = 4;
int total = 25;
double answer = total / count;
6
6.25
Analysis
num / x; is an integer expression with an integer result
– The integer result (6) of the integer expression is assigned
to a double
– Cast one of the int variables to get the result you want
double answer = (double) total / count;
–
Designing a class: Collecting tolls

Problem statement
A county is installing a toll collecting system.Trucks pulling
up to a tollbooth are required to pay a toll of $5 per axle
plus $10 per half-ton of the truck’s total weight. A display in
the booth shows the toll receipts and the number of truck
arrivals since the last collection.

Primary objects
–
Trucks

–
Axle, weight
Tollbooth

Receipts, display, toll, number
Designing a class: Truck

Behavior
–
–
–

Construct a Truck object with weight and number of axles
Get the weight
Get the number of axles
Interface
public Truck(int weight, int numAxles);
public int getWeight(); // could be double
public int getAxles();

Instance Variables
private int myWeight; // could be double
private int myNumAxles;
Designing a class: Tollbooth

Behavior
–
–
–
–

Construct a Toolbooth object
Calculate the toll
Display the data
Receipt collection
Interface
public
public
public
public

Toolbooth();
void calculateToll(Truck tr);
void receiptCollection();
void displayData();
Instance Variables
private int totalReceipts; // could be double
private int numTrucks;
Designing a class:
Implementation
Download Tollbooth.zip demo