Java Reference
In-Depth Information
condition, where
x
,
y
, and time are all equal to 0. So we can expand our pseudocode
into the following Java code:
double x = 0.0;
double y = 0.0;
double t = 0.0;
System.out.println("step\tx\ty\ttime");
System.out.println("0\t0.0\t0.0\t0.0");
for (int i = 1; i <= steps; i++) {
t += timeIncrement;
x += xIncrement;
y = yVelocity * t + 0.5 * ACCELERATION * t * t;
System.out.println(i + "\t" + round2(x) + "\t" +
round2(y) + "\t" + round2(t));
}
We can put all of these pieces together to form a complete program. Let's first look at an
unstructured version that includes most of the code in
main
. This version also includes
some new
println
statements at the beginning that give a brief introduction to the user:
1 // This program computes the trajectory of a projectile.
2
3
import
java.util.*; // for Scanner
4
5
public class
Projectile {
6 // constant for Earth acceleration in meters/second^2
7
public static final double
ACCELERATION = -9.81;
8
9
public static void
main(String[] args) {
10 Scanner console =
new
Scanner(System.in);
11
12 System.out.println("This program computes the");
13 System.out.println("trajectory of a projectile given");
14 System.out.println("its initial velocity and its");
15 System.out.println("angle relative to the");
16 System.out.println("horizontal.");
17 System.out.println();
18
19 System.out.print("velocity (meters/second)? ");
20
double
velocity = console.nextDouble();
21 System.out.print("angle (degrees)? ");
22
double
angle = Math.toRadians(console.nextDouble());
Search WWH ::
Custom Search