Question: Learning Outcomes Recognize and apply the software development phases (i)(k) Utilize Java syntax in fundamental programming algorithms (a) Recognize and apply the various input and
Learning Outcomes Recognize and apply the software development phases (i)(k) Utilize Java syntax in fundamental programming algorithms (a) Recognize and apply the various input and output devices in programming (c) Objectives In completing this project you will gain experience with the following Java features: definition of a Java class variable declaration and assignment JOptionPane dialog boxes for input and output the Math class the String class the String.format( ) method and the printf( ) method selection logic arithmetic expressions and data manipulations Problem Statement We encounter projectile motion whenever we attempt to catch a fly ball, hit a long drive, or shoot a free throw. The laws of physics, which describe projectile motion, are well known. They were first studied by Napoleons generals. To simplify the problem, we will assume that we can - consider the surface of the Earth to be a plane - ignore the effect of the drag from air friction Under the simplifying conditions above, the following formulas hold for a projectile with a launch velocity of v feet/sec and a launch angle of r (note that these expressions do not follow the Java syntax). 1. Time span of the flight: T = 2 v sin r / g 2. Maximum height: ymax = (v sin r) t - g t, where t = T/2 3. Range (distance traveled by the projectile): xmax = (v cos r) T Here g is the gravitational acceleration g = 32 ft/sec2 (in English units). In this project you implement a program such that it simulates the process of repeated attempts to hit a target with a projectile. The goal is to shoot the projectile within a 1 foot distance from the target, since such a short miss is accepted as a hit. Your program is responsible for the following tasks. CS 160 01 Spring Semester 2017 2 Compute the trajectory data of a projectile (such as the time, the maximum height and the distance as described by the formulas above) for a given launch velocity and a launch angle, in particular for an initial choice of a 45 degree angle Determine if the target is within the range for the given launch velocity, that is check if at the first attempt the distance is sort to the target with more than 1 foot; if so the process is terminated and then restarted with an increased launch velocity (note that for any velocity the longest range is attained if the launch angle is of 45 degrees) Compute the error of a shot (error = projectile range distance to target) Check if the error is less than 1 foot in absolute value (the absolute error); if so, notify the user about the result and terminate the process Offer the user four chances to modify the launch angle and try to hit the target Keep track of the smallest absolute error produced by the subsequent attempts; report the best effort to the user Analysis and requirements The analysis describes the logical structure of the problem in a way which helps us to design a solution. Input Initial input values are (i) launch velocity (feet/sec) (ii) distance to the desired target (feet) (iii) gravitational acceleration (a constant) Additional input values are the launch angles for the repeated attempts when apply. The angle must always be in the range of 0.0 45.0 degrees. Distance, velocity and launch angle are solicited from the user on JOptionPane input windows. See Figures 1, 2, 3. Figure 1 Figure 2 CS 160 01 Spring Semester 2017 3 Figure 3 Output Output messages are displayed both on JOptionPane windows and on the console. Every time a launch has been executed by the program, a report providing the details of the trajectory must be displayed as shown on Figure 4. Figure 4 Each report must contain the (1) launch velocity in feet/sec; (2) current launch angle in degrees; (3) flight time in seconds; (4) maximum height attained; (5) distance traveled by the projectile (range); (6) error with which the projectile missed the target Note that the error is a positive value when the projectile overshoots, and negative for short shots. All real numbers displayed must be rounded to the nearest hundredth. The first report is based upon launch angle of 45 degrees (which provides the longest possible range) to see if the target is within reach at all for the given velocity. If the first attempt falls short of the target, another window as shown on Figure 5 displays the information and then the program exits. CS 160 01 Spring Semester 2017 4 Figure 5 If the first shot is long enough, the window of Figure 3 shall be used to input all subsequent launch angle modifications as chosen by the user. The corresponding reports of Figure 4 show the re-calculated trajectories. Naturally, the user will try to modify the angle so as to make the projectile land nearer and nearer to the target. After each unsuccessful attempt a warning is printed to the console, see a sample on Figure 6. Shot fell short of the target. Increase the launch angle! Figure 6 Figure 7 shows a sample output on the console after all four angle modifications failed to hit the target. Shot went beyond the target. Decrease the launch angle! Shot went beyond the target. Decrease the launch angle! Shot fell short of the target. Increase the launch angle! Shot fell short of the target. Increase the launch angle! Your best shot missed the target with 4.47 feet. Figure 7 Note that it is necessary to keep track of the least absolute error occurred in the series of attempts, since it has to be reported as the last line in Figure 7 shows. Figure 8 shows a successful launch when the target was hit. Such a report is followed by the message of Figure 9 as well. Figure 8 CS 160 01 Spring Semester 2017 5 Figure 9 Relevant Formulas The basic formulas 1, 2 and 3 in the Problem Statement will be used for all trajectory computations. The input value for a launch angle shall be solicited and given in degrees. The previous formulas shall be implemented by making use of the trig methods Math.sin(angle) and Math.cos(angle ) from the Math class. These methods require the parameter angle in radians. Therefore an input angle given in degrees must be converted to radians. The conversion formula runs as follows: (angle in radians) = (angle in degrees) /180 Note that it can be used in either direction, from degrees to radians or vice versa. The value of is available as a named constant Math.PI from the Math class of the Java library. Design For this project you shall design a single class which contains all the necessary data and operations. A suggested class name is Projectile. You must decide upon the necessary import(s). The Projectile class contains the main method, which in turn contains all your code, including the variable declarations. The main method is responsible for the following tasks: opens a welcoming window as shown in Figure 10 Figure 10 declares and assigns a named constant for the gravitational acceleration; the value is 32 CS 160 01 Spring Semester 2017 6 declares variables (all double) to store projectile data velocity, distance and angle; all initialized to 0 solicits the input values as explained in the Analysis section, see the templates in Figures 1, 2 and 3; if either of these input is the empty string or null (Cancel button), the message as shown in Figure 11 displayed and the program exits; valid input parsed and saved in the relevant variables Figure 11 computes all the trajectory and output data and saves those in relevant variables (declare and use the necessary variables as specified in the class description below) builds up and stores the output message in a single string variable (the full content of Figures 4, 8) displays the output windows numbers in the output are formatted to the nearest hundredth; for this purpose, use the String.format( ) method for JOptionPane output; for the console both String.format( ) and printf( ) are applicable; DecimalFormat class is also permitted as explained in the 5th Edition of Gaddis utilizes if and/or if-else logic to decide if additional launches are necessary and repeats the operations at most four times as needed (note: heavy code repetition will be necessary to cover all four cases, since using loops is not allowed) terminates the program when it is due The Projectile class See the detailed class description below. You may declare additional local variables in the main method, but do not leave variable declarations in the code which never get used. Projectile METHOD main The method opens Figure 10 and input windows (see Figures 1, 2, 3) to obtain the initial data. The input values are assigned to the corresponding data fields. The method computes the flight time, maximum height and range. The results displayed on a message window (see Figure 4). Displays Figures 5 11 as needed After the last attempt, the program exits. Local variables in main GRAVITATION named constant, the value is 32. CS 160 01 Spring Semester 2017 7 distanceToTarget double; to store the distance in feet to the desired target (input) initialVelocity double; to store the projectile's initial velocity in feet/second (input) launchAngle double; to store the current input for launch angle in degrees (input) radian double; to store the value of angle in radians (calculated) flightTime double; to store the flight time of the projectile as defined by formula 1 in the description (calculated) highestPoint double; to store the maximum height of the projectile as defined by formula 2 in the description (calculated) distanceTraveled double; to store the distance traveled by the projectile as defined by formula 3 in the description (calculated) error double; to store the difference between distance traveled and distance to target (calculated) minError double; to store the least absolute error; updated every time a new error value was generated (calculated) trajectory String; to store the current output message built upon the trajectory data Testing Test your program with input values shown in the description. See if your results match the output data. Additional Requirements and Hints 1. Having your program tested, run the program with a new set of input data of your own choice as well. In that case the distance to target must be at least 500 feet. Copy your trajectory report as a comment block after the class code. 2. You are NOT allowed to use iteration structures (loops) to code the repeated attempts. The relevant part of the code that calculates and displays the trajectory results must be copied four times into the program. Here is the pseudo-code version of the code you must copy four times: if error positive send overshoot message to the console else send undershoot message to the console solicit new input for launch angle calculate radian re-calculate all trajectory data calculate error update minError compose output message CS 160 01 Spring Semester 2017 8 display output message if absolute error less than 1 display success message on window terminate the program 3. Use the Math.abs( ) method to calculate the absolute value of the error, when you make a decision about the accuracy of the shot. 4. Set up a variable minError as suggested in the class description. Every time the program generates a new error, update minError such that it stores the least absolute error occurred this far. Use the Math.abs( ) and Math.min( ) methods for this purpose. 5. Use the Math.sin( ) and Math.cos( ) methods for the sin and cosine function evaluations. The introduction of the Math class in the book (p.62) is very limited, for more details, including the functions needed in the Project read slides MathClass posted on Blackboard 6. The first input for launch angle must be 45 degrees. After the first attempt you choose the four additional modified angles as you see it best 7. Do not round the numeric values while needed in calculations. Apply formatting only when the output message (a String value) is composed
package projectile; import javax.swing.JOptionPane; /** * * @author ZolmanAaron */ public class Project1 { /** * @param args the command line arguments */ public static void main(String[] args) {
final double g = 32;
double distanceToTarget, initialVelocity, angle, bestAngle;
double closestDistance = Double.MAX_VALUE;
bestAngle = 0;
initialVelocity = 0;
distanceToTarget = 0;
angle = 0;
String launchVelocity;
String distance;
String angleOfLaunch;
//Displays screens and tells whether user makes correct input or not
JOptionPane.showMessageDialog(null,"Welcome to the shooting range!");
boolean correctInput = false;
distance = JOptionPane.showInputDialog("Enter distance to target in" + " feet: ");
if (distance == null || distance.isEmpty()) System.exit(0); distanceToTarget = Double.parseDouble(distance);
if(!correctInput){ launchVelocity = JOptionPane.showInputDialog("Enter launch velocity in" + " feet/sec: ");
if (launchVelocity == null || launchVelocity.isEmpty()) System.exit(0); initialVelocity = Double.parseDouble(launchVelocity);
correctInput = checkCorrectInput(distanceToTarget, initialVelocity, g); }
boolean hit = false;
//Will repeat the number of attempts 4 times before displaying best
if(i = 0; i < 4; i++){ double range = 0; angleOfLaunch = JOptionPane.showInputDialog("Enter Launch Angle" + " in degrees: ");
if (angleOfLaunch == null || angleOfLaunch.isEmpty()) System.exit(0);
angle = Double.parseDouble(angleOfLaunch);
range = getRange(initialVelocity, g, angle);
//makes the user re enter value if not between 0 - 45
if(angle < 0 || angle > 45.0){
} else{
} if (Math.abs(distanceToTarget - range) < closestDistance) {
//Will log the best attempt closestDistance = Math.abs(distanceToTarget - range);
bestAngle = angle; }
if (Math.abs(distanceToTarget - range) < 1.0) { hit = true;
} else {
// Report if missed or hit and best attempt
String outputText = "Missed " + getReport(distanceToTarget, range, initialVelocity, angle, g);
System.out.println(outputText); }
} String bestAttempt;
if (hit) { bestAttempt = "Hit " + getReport(distanceToTarget, getRange(initialVelocity, g, bestAngle), initialVelocity, angle, g);
} else {
bestAttempt = "Best Overall Attempt " + getReport(distanceToTarget, getRange(initialVelocity, g, bestAngle), initialVelocity, angle, g);
} // Display final outcomes of entered stats
System.out.println(bestAttempt); }
private static String getReport(double distanceTraveled, double range, double initialVelocity, double angle, double g) { StringBuilder str = new StringBuilder(); JOptionPane.showMessageDialog(null,"launch velocity: " + initialVelocity + " feet/sec" + " " + "launch angle: " + angle + " degrees" + " " + "flight time: " + flightTime(initialVelocity,angle,g) + " seconds" + " " + "maximum height: " + height(initialVelocity,angle,g) + " feet" + " " + "distance traveled: " + distanceTraveled + " feet" + " " + "target missed by: " + (distanceTraveled - range) + " feet" ); return str.toString(); }
//Way to find if the velocity can attain the distance
private static boolean checkCorrectInput(double distance, double velocity, double g) { double range = getRange(velocity, g, 45.0);
if (distance - range > 1.0) return false;
else
return true; }
//Way to find the flight time total
private static double flightTime(double velocity, double angle, double g)
{ double flightTime = 2*velocity*Math.sin(Math.toRadians(angle))/g;
return flightTime; }
//Way to find the range total
private static double getRange(double velocity, double g, double angle)
{ double range = velocity * velocity * Math.sin(2 * Math.toRadians(angle)) / g;
return range; }
//Way to find the max height
private static double height(double velocity, double angle, double g) {
double height = Math.pow(velocity*Math.sin(Math.toRadians(angle)),2)/ (2*g) ;
return height; } }
Used loops and wasn't supposed to, need helping fixing the code.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
