Java Reference
In-Depth Information
2
18.07
17.23
0.94
3
27.1
22.61
1.41
4
36.14
25.84
1.87
5
45.17
26.92
2.34
6
54.21
25.84
2.81
7
63.24
22.61
3.28
8
72.28
17.23
3.75
9
81.31
9.69
4.22
10
90.35
0.0
4.69
From the log of execution, you can see that the projectile reaches a maximum
height of 26.92 meters after 2.34 seconds (the fifth step) and that it lands 90.35
meters from where it began after 4.69 seconds (the tenth step).
This version of the program works, but we don't generally want to include so
much code in the main method. The next section explores how to break up the pro-
gram into smaller pieces.
Structured Solution
There are three major blocks of code in the main method of the Projectile pro-
gram: a series of println statements that introduce the program to the user, a series
of statements that prompt the user for the three values used to produce the table, and
then the code that produces the table itself.
So, in pseudocode, the overall structure looks like this:
give introduction.
prompt for velocity, angle and number of steps.
produce table.
The first and third steps are easily turned into methods, but not the middle step.
This step prompts the user for values that we need to produce the table. If we turned
it into a method, it would have to somehow return three values back to main . A
method can return only a single value, so unfortunately we can't turn this step into a
method. We could turn it into three different methods, one for each of the three val-
ues, but each of those methods would be just two lines long, so it's not clear that
doing so would improve the overall structure.
The main improvement we can make, then, is to split off the introduction and the table
into separate methods. Another improvement we can make is to turn the physics displace-
ment formula into its own method. It is always a good idea to turn equations into meth-
ods. Introducing those methods, we get the following structured version of the program:
1 // This program computes the trajectory of a projectile.
2
3 import java.util.*; // for Scanner
4
5 public class Projectile2 {
 
Search WWH ::




Custom Search