CS 151 Fall 2007 Lab 4:
Constants,
Static Methods, Numeric Types, & Calculations
The goal for this lab is to learn more about the various
numeric types that Java supports.
These primitive types include: short, int, long, double, float, boolean,
char, byte. We will use static
methods from the Math class and some physical constants you will define to
perform some simple numerical calculations.
- Open
BlueJ either by selecting it from the Dock or navigating to it in the
Applications folder and double clicking it.
- Mount your network
directory/folder so that you can access the lab after you leave Olin
323. Go to the Finder and
from the
Go menu select Connect to Server.... Type afp://fileserver1 or choose it from the
list of selections and select the Personal volume
when prompted.
- From
the Project menu select New Project. Select your computer from the drop
down menu. Then scroll down
and open the Volumes folder and then the Personal folder inside it. Scroll down the long list of
folders until your find yours.
Create a project called "Lab4" in your personal network
folder.
- From the BlueJ help
menu, select Java Class Libraries to open up a browser window with the
Java language documentation.
Select the Math class which is in the java.lang package. This class contains a number of
useful numeric constants and functions that you will need from time to
time. Unlike the classes we
have worked with until now, we won't actually create any objects of this
class. Instead we utilize
some of its static methods.
- Create
a class called "Newton" in honor of the famous scientist of the
same name. As usual, remove
the default method and instance variable BlueJ creates for you in the
class.
- Create a main method
for your class.
public static void
main(String[] args)
{
}
- Add the following
statements to your main method (Note that copying them from this page may
cause strange errors). Why
add one to the expression in the second statement?
System.out.println("The
largest and smallest number in the class called int are " +
Integer.MAX_VALUE + " and " + Integer.MIN_VALUE);
System.out.println("This means there are
" +
(Integer.MAX_VALUE - Integer.MIN_VALUE + 1) + " different int
values");
- Compile,
fix any error then run the main method from the BlueJ project window. Remember, you do this by
control-clicking on the Newton class and then selecting "void main
(String [] args)" from the menu. Click OK when prompted for parameters, since we have
none to give the method. Did
the second command give you what you were expecting? This is due to an overflow
condition. By default since
you are adding ints, Java expresses the answer as an int. But as the first
line tells you this value is too big to be expressed as an int. We need to have Java interpret the
numbers as a different type.
This is called a cast.
You cast a variable, value or expression by preceding it with the
desired type in parenthesis.
Change the second statement to
System.out.println("This
means there are " +
(long) (Integer.MAX_VALUE - Integer.MIN_VALUE + 1) + "
different int values");
- Compile
are rerun. Did this fix the
problem? Why not? Try the following instead
System.out.println("This
means there are " +
((long)
Integer.MAX_VALUE - (long) Integer.MIN_VALUE + 1) +
"
different int values");
- Add a static method
before your main method called log2 that computes the logarithm base 2 of
a given number.
Mathematicians like to use e (Math.E) for their logarithm base, but
we computer scientists prefer 2.
/**
* Computes the logarithm base 2 of the
specified number.
* @param value a float to compute the
log of
* @return the log base 2 as a float
*/
public
static double log2(double value)
{
return
Math.log(value)/Math.log(2);
}
- Replace the expression
((long) Integer.MAX_VALUE -
(long) Integer.MIN_VALUE + 1)
in your main method with
intValues.
Define this variable as a long in your main method and initialize
it with the above expression.
//total number of different int values
long intValue = ((long)
Integer.MAX_VALUE - (long) Integer.MIN_VALUE + 1);
- Add a public constant
to your Newton class called BITS_PER_BYTE and set it equal to 8.
- At the end of your main
method add the following lines
short
bitsStored = log2(intValues);
System.out.println("The
int class uses " + bitsStored + " bits or " +
bitsStored/BITS_PER_BYTE
+ " bytes to store each value.");
Why
does the compiler gives you a warning?
Appease it by explicitly casting the result of your log2
method on intValues as a short.
- Add a
constant called EARTH_GRAVITY to your class.
//The
gravitational acceleration at the surface of the earth (feet/second
squared)
public
static final EARTH_GRAVITY = 32.2;
//The gravitational acceleration
at the surface of the earth (meters/second squared)
public
static final EARTH_GRAVITY = 9.81;
- Newton says that if
your initial velocity is v and you accelerate at a constant rate a, then
you travel
d = a*t2
+ v*t
travel distance d after t seconds.
Add a method to your class (before the main method) called
distanceTraveled that returns a double and takes three parameters all of
which are double.
/**
*
Calculates the distance traveled at a constant acceleration.
*
@param accel the constant rate of acceleration in meters/second squared
*
@param velocity the initial velocity in meters/second
*
@param time the time in seconds
*/
public
static double distanceTraveled(double accel, double initVelocity, double time)
{
return (accel*time+initVelocity)*time;
}
- Test your method by control
clicking the Newton class and selecting the distanceTraveled method. You can use your EARTH_GRAVITY
constant by typing Newton.EARTH_GRAVITY or an expression involving it in
one of the parameter boxes.
- Suppose instead you
know how far you have to travel and want to know how long it will take you
to get there at some constant rate of acceleration. You want to solve the equation
a*t2 + v*t – d. Create a method called travelTime
that returns a double and takes three parameters all of which are doubles.
/**
* Calculates the time needed to
travel a given distance in meters at a constant
* rate of acceleration in
meters/second squared from an initial velocity in meters/second.
* @param accel
* @param initVelocity
* @param distance
* @return time in seconds
*/
public static double
travelTime(double accel, double initVelocity, double distance)
{
//equation we are
applying quadratic formula to is accel*time^2+initVelocity*time-distance
double root =
Math.sqrt(initVelocity*initVelocity + 4*accel*distance);
return (-initVelocity +
root)/(2*accel);
}
- Compile and test with
an acceleration of one Earth gravity, initial velocity of 2 m/s and a
distance of 1000 meters. It
should take only ten seconds to make that trip!
- Try our out some astronomical
trips to the moon, sun, Mars, etc. at different accelerations. The average distance from the
Earth to the Moon is 384,403 kilometers (238,857
miles), from the Earth to the Sun is approximately 2.5 x 1020
meters. See www.wikipedia.org
or your favorite astronomy site for other distances. You can also use your method to figure
out how long it would take a penny to get from the top of the Empire State
Building in New York City to the ground (381 meters or 1250 feet). I don't advocate dropping pennies
or any other object from there!
- Add a method called
base2To10 that takes a String representing a binary number and returns its
corresponding base 10 integer.
The static method Math.pow(num1,num2) returns the result of num1
raised to the num2 power, i.e. num1num2. Add comments to document the
method and fill in the missing part (????)
public static int base2To10(String binaryNumber)
{
//store
the result in variable
int result =0;
for (int
pos=0; pos<binaryNumber.length();pos++)
{
result =
result + ????;
}
return
result;
}