Exercise 2: Using Operators and Type Casting
The objective of this exercise is to give you practice using operators and type casting.
Task 1 – Calculating Ages Using Operators
In this task, you use operators to calculate age in minutes and milliseconds. Follow thesesteps to create a
Person
class that calculates various ages:1.
Go to the
data_types
directory.2.
Enter the
Person
class from this module.
Note –
A copy of this code is provided at the end of these instructions.3.
Add the following code to your
Person
class:a.
Add a line to calculate and print your age in minutes.b.
Add a line to calculate and print your age in milliseconds (1/1000 of a second).4.
Test the program using the
PersonTest
class with the ages of 1, 24, and 100.
Task 2 – Using Casting to Prevent Data Loss
In this task, you use casting to ensure that data loss does not occur in your programs.Follow these steps to create an
Order
class:5.
Write a class called
Order
that contains two variables of type
int
called
int1
and
int2
and a method called
calculateTotal
.6.
Write a
calculateTotal
method that multiplies the two integer values and printsthe result.7.
Test the program using the
OrderTest
class. Test the program with:a.
One-digit
int
typesb.
Five-digit
int
typesc.
Nine-digit
int
typesEnsure that you get the same result with the program as you do when doing eachcalculation manually (or using a calculator).
Note –
Remember to cast the two integers so that the temporary containeris large enough to hold the result of multiplying two 5-digit or 9-digit
int
types. See the caution message earlier in this module.
Leave a Comment
http://www.tecnoesis.com, http://tecnoesis.wordpress.com/