Question

In this project you implement a program such that it simulates the process of repeated attempts...

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.

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

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.

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.

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

 declares and assigns a named constant for the gravitational acceleration; the value is 32

 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, 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

 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

 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

Homework Answers

Answer #1

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Projectile {

   public static void main(String[] args) {

       final double g = 32;
       double velocity = 0, distance = 0, angle = 0;
       double bestAngle = 0, bestDistance = Double.MAX_VALUE;

       JFrame frame = new JFrame("Welcome");
       boolean validInput = false;
       // Display welcome Message
       JOptionPane.showMessageDialog(frame, "Welcome...");
       // Accept distance value
       String distanceStr = JOptionPane.showInputDialog(frame,
               "Enter Traget Distance");
       ;
       if (distanceStr == null || distanceStr.isEmpty())
           System.exit(0);
       distance = Double.parseDouble(distanceStr);
       while (!validInput) {
           // Accept launch velocity value
           String velocityStr = JOptionPane.showInputDialog(frame,
                   "Enter Launch Velocity");
           if (velocityStr == null || velocityStr.isEmpty())
               System.exit(0);
           velocity = Double.parseDouble(velocityStr);
           validInput = checkValidInput(distance, velocity, g);
       }
       boolean hit = false;
       // Attempt 4 times
       double range = 0;
       do {
           String angleStr = JOptionPane.showInputDialog(frame,
                   "Enter Launch Angle");
           if (angleStr == null || angleStr.isEmpty())
               System.exit(0);
           angle = Double.parseDouble(angleStr);
           range = getRange(velocity, g, angle);
       } while (angle < 0 || angle > 45.0); // Re-enter angle value is value is
                                               // not in range 0 - 45.0
       if (Math.abs(distance - range) < bestDistance) {
           // Save best attempt
           bestDistance = Math.abs(distance - range);
           bestAngle = angle;
       }
       if (Math.abs(distance - range) < 1.0) {
           hit = true;
       } else {
           // Display report
           String outputText = "MISSED!\n"
                   + getReport(distance, range, velocity, angle, g);
           System.out.println(outputText);
           JOptionPane.showMessageDialog(frame, outputText);
       }
       if (!hit) {
           range = 0;
           do {
               String angleStr = JOptionPane.showInputDialog(frame,
                       "Enter Launch Angle");
               if (angleStr == null || angleStr.isEmpty())
                   System.exit(0);
               angle = Double.parseDouble(angleStr);
               range = getRange(velocity, g, angle);
           } while (angle < 0 || angle > 45.0); // Re-enter angle value is
                                                   // value is not in range 0 -
                                                   // 45.0
           if (Math.abs(distance - range) < bestDistance) {
               // Save best attempt
               bestDistance = Math.abs(distance - range);
               bestAngle = angle;
           }
           if (Math.abs(distance - range) < 1.0) {
               hit = true;
           } else {
               // Display report
               String outputText = "MISSED!\n"
                       + getReport(distance, range, velocity, angle, g);
               System.out.println(outputText);
               JOptionPane.showMessageDialog(frame, outputText);
           }
       }

       if (!hit) {
           range = 0;
           do {
               String angleStr = JOptionPane.showInputDialog(frame,
                       "Enter Launch Angle");
               if (angleStr == null || angleStr.isEmpty())
                   System.exit(0);
               angle = Double.parseDouble(angleStr);
               range = getRange(velocity, g, angle);
           } while (angle < 0 || angle > 45.0); // Re-enter angle value is
                                                   // value is not in range 0 -
                                                   // 45.0
           if (Math.abs(distance - range) < bestDistance) {
               // Save best attempt
               bestDistance = Math.abs(distance - range);
               bestAngle = angle;
           }
           if (Math.abs(distance - range) < 1.0) {
               hit = true;
           } else {
               // Display report
               String outputText = "MISSED!\n"
                       + getReport(distance, range, velocity, angle, g);
               System.out.println(outputText);
               JOptionPane.showMessageDialog(frame, outputText);
           }
       }
       if (!hit) {
           range = 0;
           do {
               String angleStr = JOptionPane.showInputDialog(frame,
                       "Enter Launch Angle");
               if (angleStr == null || angleStr.isEmpty())
                   System.exit(0);
               angle = Double.parseDouble(angleStr);
               range = getRange(velocity, g, angle);
           } while (angle < 0 || angle > 45.0); // Re-enter angle value is
                                                   // value is not in range 0 -
                                                   // 45.0
           if (Math.abs(distance - range) < bestDistance) {
               // Save best attempt
               bestDistance = Math.abs(distance - range);
               bestAngle = angle;
           }
           if (Math.abs(distance - range) < 1.0) {
               hit = true;
           } else {
               // Display report
               String outputText = "MISSED!\n"
                       + getReport(distance, range, velocity, angle, g);
               System.out.println(outputText);
               JOptionPane.showMessageDialog(frame, outputText);
           }
       }
       String str = "";
       if (hit) {
           str = "HIT!!!\n"
                   + getReport(distance, getRange(velocity, g, bestAngle),
                           velocity, angle, g);
       } else {
           str = "Best Attempt\n"
                   + getReport(distance, getRange(velocity, g, bestAngle),
                           velocity, angle, g);
       }
       // Display final report
       System.out.println(str);
       JOptionPane.showMessageDialog(frame, str);
   }

   // Method to get projectile details as string
   private static String getReport(double distance, double range,
           double velocity, double angle, double g) {
       StringBuilder str = new StringBuilder();
       str.append("Target Distance: " + String.format("%.2f", distance) + "\n");
       str.append("Launch Velocity: " + String.format("%.2f", velocity) + "\n");
       str.append("Launch Angle: " + String.format("%.2f", angle) + "\n");
       str.append("Range: " + String.format("%.2f", range) + "\n");
       str.append("Time of flight: "
               + String.format("%.2f", findTimeOfFlight(velocity, angle, g))
               + "\n");
       str.append("Maximum height reached: "
               + String.format("%.2f", findMaximumHeight(velocity, angle, g))
               + "\n");
       str.append("Correction in Range Required: "
               + String.format("%.2f", distance - range));
       return str.toString();
   }

   // Method to find maximum height
   private static double findMaximumHeight(double velocity, double angle,
           double g) {
       double height = Math.pow(velocity * Math.sin(Math.toRadians(angle)), 2)
               / (2 * g);
       return height;
   }

   // Method to find time of flight
   private static double findTimeOfFlight(double velocity, double angle,
           double g) {
       double time = 2 * velocity * Math.sin(Math.toRadians(angle)) / g;
       return time;
   }

   // Method to check if launch velocity can attain target distance
   private static boolean checkValidInput(double distance, double velocity,
           double g) {
       double range = getRange(velocity, g, 45.0);
       if (distance - range > 1.0)
           return false;
       else
           return true;
   }

   // Method to calculate range of the projectile
   private static double getRange(double velocity, double g, double angle) {
       double range = velocity * velocity
               * Math.sin(2 * Math.toRadians(angle)) / g;
       return range;
   }

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Homework 3 As you know very well from physics, if you hit a ball forward with...
Homework 3 As you know very well from physics, if you hit a ball forward with a certain angle and a certain speed, it makes an orbital movement. The height of the ball is determined by the equation given below. y(t)=y_0+v_y0 t-1/2 gt^2 Where y0 is the first location of the ball, vy0 is the initial vertical velocity of the ball and g is the gravitational acceleration. After the ball is thrown, the horizontal distance is determined by the following...
Question: Squares. Write a program class named SquareDisplay that asks the user for a positive integer...
Question: Squares. Write a program class named SquareDisplay that asks the user for a positive integer no greater than 15. The program should then display a square on the screen using the character ‘X’. The number entered by the user will be the length of each side of the square. For example, if the user enters 5, the program should display the following:       XXXXX       XXXXX       XXXXX       XXXXX       XXXXX INPUT and PROMPTS. The program prompts for an integer as follows: "Enter...
You will write a program that loops until the user selects 0 to exit. In the...
You will write a program that loops until the user selects 0 to exit. In the loop the user interactively selects a menu choice to compress or decompress a file. There are three menu options: Option 0: allows the user to exit the program. Option 1: allows the user to compress the specified input file and store the result in an output file. Option 2: allows the user to decompress the specified input file and store the result in an...
For this assignment, you will be creating a simple “Magic Number” program. When your program starts,...
For this assignment, you will be creating a simple “Magic Number” program. When your program starts, it will present a welcome screen. You will ask the user for their first name and what class they are using the program for (remember that this is a string that has spaces in it), then you will print the following message: NAME, welcome to your Magic Number program. I hope it helps you with your CSCI 1410 class! Note that "NAME" and "CSCI...
Written in MASM Assembly Problem Definition: Write a program to calculate Fibonacci numbers. • Display the...
Written in MASM Assembly Problem Definition: Write a program to calculate Fibonacci numbers. • Display the program title and programmer’s name. Then get the user’s name, and greet the user. • Prompt the user to enter the number of Fibonacci terms to be displayed. Advise the user to enter an integer in the range [1 .. 46]. • Get and validate the user input (n). • Calculate and display all of the Fibonacci numbers up to and including the nth...
Subject- ( App Development for Web) ( language C#, software -visual studio) Exact question is-Firstly the...
Subject- ( App Development for Web) ( language C#, software -visual studio) Exact question is-Firstly the console calculator is created which perform multiply,divide,sub and add, operation and it accept all type of data (divide by 0 case as well ).Now the main motive is to create the library project from the console calculator project .Than we have to create a unit test project which test the functionality of added library.Make test like Test 1. multiply two positive number,Test 2. Add...
Part A. Input Validation (Name your C program yourLastName_yourFirstName_Lab4a.c) 1. Place the code you developed in...
Part A. Input Validation (Name your C program yourLastName_yourFirstName_Lab4a.c) 1. Place the code you developed in Lab 2 to obtain a diameter value from the user and compute the volume of a sphere (we assumed that to be the shape of a balloon) in a new program, and implement the following restriction on the user’s input: the user should enter a value for the diameter which is at least 8 inches but not larger than 60 inches. Using an if-else...
This will be my third time submitting this question. THERE SHOULD BE NO USE OF CSS...
This will be my third time submitting this question. THERE SHOULD BE NO USE OF CSS OR SWITCH STATEMENTS IN THE JAVASCRIPT. Even though there is stylesheet in the HTML file do no create a new one. Project Standards: Students will use click events to capture user input. Students will use variables to store information needed by their application and keep track of their program’s state. Students will use conditionals to control project flow. Project Task You will be building...
In this assignment, you will develop a Python program that will process applications for gala-type events...
In this assignment, you will develop a Python program that will process applications for gala-type events at a local dinner club. The club, Gala Events Inc., is currently booking events for the upcoming holidays. However, the club has the following restrictions: Due to the physical size of the building, its maximum occupancy for any event is 100—not including the club staff. Since local regulations do not permit the sale of alcoholic beverages after midnight, the maximum length of any event...
I've posted this question like 3 times now and I can't seem to find someone that...
I've posted this question like 3 times now and I can't seem to find someone that is able to answer it. Please can someone help me code this? Thank you!! Programming Project #4 – Programmer Jones and the Temple of Gloom Part 1 The stack data structure plays a pivotal role in the design of computer games. Any algorithm that requires the user to retrace their steps is a perfect candidate for using a stack. In this simple game you...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT