Java Reference
In-Depth Information
3.4 Case Study: Projectile Trajectory
It's time to pull together the threads of this chapter with a more complex example
that will involve parameters, methods that return values, mathematical computations,
and the use of a Scanner object for console input.
Physics students are often asked to calculate the trajectory that a projectile will
follow, given its initial velocity and its initial angle relative to the horizontal. For
example, the projectile might be a football that someone has kicked. We want to
compute the path it follows given Earth's gravity. To keep the computation reason-
able, we will ignore air resistance.
There are several questions relating to this problem that we might want to answer:
When does the projectile reach its highest point?
How high does it reach?
How long does it take to come back to the ground?
How far does it land from where it was launched?
There are several ways to answer these questions. One simple approach is to provide
a table that displays the trajectory step by step, indicating the x position, y position, and
elapsed time.
To make such a table, we need to obtain three values from the user: the initial
velocity, the angle relative to the horizontal, and the number of steps to include in the
table we will produce. We could ask for the velocity in either meters/second or
feet/second, but given that this is a physics problem, we'll stick to the metric system
and ask for meters/second.
We also have to think about how to specify the angle. Unfortunately, most of the
Java methods that operate on angles require angles in radians rather than degrees. We
could request the angle in radians, but that would be highly inconvenient for the user,
who would be required to make the conversion. Instead, we can allow the user to
enter the angle in degrees and then convert it to radians using the built-in method
Math.toRadians .
So, the interactive part of the program will look like this:
Scanner console = new Scanner(System.in);
System.out.print("velocity (meters/second)? ");
double velocity = console.nextDouble();
System.out.print("angle (degrees)? ");
double angle = Math.toRadians(console.nextDouble());
System.out.print("number of steps to display? ");
int steps = console.nextInt();
Notice that for the velocity and angle we call the nextDouble method of the
console object, because we want to let the user specify any number (including one
with a decimal point), but for the number of steps we call nextInt , because the num-
ber of lines in our table needs to be an integer.
 
Search WWH ::




Custom Search