SlideShare a Scribd company logo
1 of 8
Download to read offline
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
Solution
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! "
+ 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! "
+ 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! "
+ 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! "
+ getReport(distance, range, velocity, angle, g);
System.out.println(outputText);
JOptionPane.showMessageDialog(frame, outputText);
}
}
String str = "";
if (hit) {
str = "HIT!!! "
+ getReport(distance, getRange(velocity, g, bestAngle),
velocity, angle, g);
} else {
str = "Best Attempt "
+ 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) + " ");
str.append("Launch Velocity: " + String.format("%.2f", velocity) + " ");
str.append("Launch Angle: " + String.format("%.2f", angle) + " ");
str.append("Range: " + String.format("%.2f", range) + " ");
str.append("Time of flight: "
+ String.format("%.2f", findTimeOfFlight(velocity, angle, g))
+ " ");
str.append("Maximum height reached: "
+ String.format("%.2f", findMaximumHeight(velocity, angle, g))
+ " ");
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;
}
}

More Related Content

Similar to In this project you implement a program such that it simulates the p.pdf

golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
 
Flight Landing Analysis
Flight Landing AnalysisFlight Landing Analysis
Flight Landing AnalysisTauseef Alam
 
The purpose of this assignment is to have you write a Java program us.docx
 The purpose of this assignment is to have you write a Java program us.docx The purpose of this assignment is to have you write a Java program us.docx
The purpose of this assignment is to have you write a Java program us.docxKomlin1
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyRalph Johnson
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
40+ examples of user defined methods in java with explanation
40+ examples of user defined methods in java with explanation40+ examples of user defined methods in java with explanation
40+ examples of user defined methods in java with explanationHarish Gyanani
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.pptMahyuddin8
 
Introduction to go
Introduction to goIntroduction to go
Introduction to goJaehue Jang
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxTseChris
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)Ishin Vin
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorNeeraj Kaushik
 
I worte the code according to the requirement.And also I wrote the c.pdf
I worte the code according to the requirement.And also I wrote the c.pdfI worte the code according to the requirement.And also I wrote the c.pdf
I worte the code according to the requirement.And also I wrote the c.pdfsudhinjv
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)yap_raiza
 
3- In the program figurespointers we have a base class location and va.pdf
3- In the program figurespointers we have a base class location and va.pdf3- In the program figurespointers we have a base class location and va.pdf
3- In the program figurespointers we have a base class location and va.pdfatozshoppe
 
Class program and uml in c++
Class program and uml in c++Class program and uml in c++
Class program and uml in c++Osama Al-Mohaia
 

Similar to In this project you implement a program such that it simulates the p.pdf (18)

golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Flight Landing Analysis
Flight Landing AnalysisFlight Landing Analysis
Flight Landing Analysis
 
Ch3
Ch3Ch3
Ch3
 
The purpose of this assignment is to have you write a Java program us.docx
 The purpose of this assignment is to have you write a Java program us.docx The purpose of this assignment is to have you write a Java program us.docx
The purpose of this assignment is to have you write a Java program us.docx
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
40+ examples of user defined methods in java with explanation
40+ examples of user defined methods in java with explanation40+ examples of user defined methods in java with explanation
40+ examples of user defined methods in java with explanation
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.ppt
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptx
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression Calculator
 
I worte the code according to the requirement.And also I wrote the c.pdf
I worte the code according to the requirement.And also I wrote the c.pdfI worte the code according to the requirement.And also I wrote the c.pdf
I worte the code according to the requirement.And also I wrote the c.pdf
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
3- In the program figurespointers we have a base class location and va.pdf
3- In the program figurespointers we have a base class location and va.pdf3- In the program figurespointers we have a base class location and va.pdf
3- In the program figurespointers we have a base class location and va.pdf
 
Class program and uml in c++
Class program and uml in c++Class program and uml in c++
Class program and uml in c++
 
7 functions
7  functions7  functions
7 functions
 

More from fathimafancy

Write the program segment necessary to Test the C flag. i. If the .pdf
Write the program segment necessary to  Test the C flag.  i. If the .pdfWrite the program segment necessary to  Test the C flag.  i. If the .pdf
Write the program segment necessary to Test the C flag. i. If the .pdffathimafancy
 
Why must Group IV be treated with (NH4)2CO3 in basic solution What .pdf
Why must Group IV be treated with (NH4)2CO3 in basic solution What .pdfWhy must Group IV be treated with (NH4)2CO3 in basic solution What .pdf
Why must Group IV be treated with (NH4)2CO3 in basic solution What .pdffathimafancy
 
what is IOT what us SolutionAns. IOT stands for Internet of Th.pdf
what is IOT what us SolutionAns. IOT stands for Internet of Th.pdfwhat is IOT what us SolutionAns. IOT stands for Internet of Th.pdf
what is IOT what us SolutionAns. IOT stands for Internet of Th.pdffathimafancy
 
What is the difference between a BSS and a ESSSolutionBSS sta.pdf
What is the difference between a BSS and a ESSSolutionBSS sta.pdfWhat is the difference between a BSS and a ESSSolutionBSS sta.pdf
What is the difference between a BSS and a ESSSolutionBSS sta.pdffathimafancy
 
What is the role of capsid and nucleocapsid proteins during the life.pdf
What is the role of capsid and nucleocapsid proteins during the life.pdfWhat is the role of capsid and nucleocapsid proteins during the life.pdf
What is the role of capsid and nucleocapsid proteins during the life.pdffathimafancy
 
What distinguish between managerial and financial accounting as to (.pdf
What distinguish between managerial and financial accounting as to (.pdfWhat distinguish between managerial and financial accounting as to (.pdf
What distinguish between managerial and financial accounting as to (.pdffathimafancy
 
There is a lack of spirituality in a person that cheats because they.pdf
There is a lack of spirituality in a person that cheats because they.pdfThere is a lack of spirituality in a person that cheats because they.pdf
There is a lack of spirituality in a person that cheats because they.pdffathimafancy
 
select the answer a general search engine differs from a subject di.pdf
select the answer a general search engine differs from a subject di.pdfselect the answer a general search engine differs from a subject di.pdf
select the answer a general search engine differs from a subject di.pdffathimafancy
 
State briefly what functions an Engineering Services Department in a.pdf
State briefly what functions an Engineering Services Department in a.pdfState briefly what functions an Engineering Services Department in a.pdf
State briefly what functions an Engineering Services Department in a.pdffathimafancy
 
Satellites in geosynchronous orbit have the desirable property of re.pdf
Satellites in geosynchronous orbit have the desirable property of re.pdfSatellites in geosynchronous orbit have the desirable property of re.pdf
Satellites in geosynchronous orbit have the desirable property of re.pdffathimafancy
 
Research and discuss an incident where it was discovered that a Remo.pdf
Research and discuss an incident where it was discovered that a Remo.pdfResearch and discuss an incident where it was discovered that a Remo.pdf
Research and discuss an incident where it was discovered that a Remo.pdffathimafancy
 
Please review the attached casescenario. You are Bill. Feel free to.pdf
Please review the attached casescenario. You are Bill. Feel free to.pdfPlease review the attached casescenario. You are Bill. Feel free to.pdf
Please review the attached casescenario. You are Bill. Feel free to.pdffathimafancy
 
Please make sure it works Ive been struggling with this and so far.pdf
Please make sure it works Ive been struggling with this and so far.pdfPlease make sure it works Ive been struggling with this and so far.pdf
Please make sure it works Ive been struggling with this and so far.pdffathimafancy
 
Please explain the physiological mechanism for enlarged lymph nodes..pdf
Please explain the physiological mechanism for enlarged lymph nodes..pdfPlease explain the physiological mechanism for enlarged lymph nodes..pdf
Please explain the physiological mechanism for enlarged lymph nodes..pdffathimafancy
 
multiple choiceAssuming that the probability for each shot is .pdf
multiple choiceAssuming that the probability for each shot is .pdfmultiple choiceAssuming that the probability for each shot is .pdf
multiple choiceAssuming that the probability for each shot is .pdffathimafancy
 
Mathematical Statistics.....Could answer be typed (is there any link.pdf
Mathematical Statistics.....Could answer be typed (is there any link.pdfMathematical Statistics.....Could answer be typed (is there any link.pdf
Mathematical Statistics.....Could answer be typed (is there any link.pdffathimafancy
 
Modify the Stack class given in the book in order for it to store do.pdf
Modify the Stack class given in the book in order for it to store do.pdfModify the Stack class given in the book in order for it to store do.pdf
Modify the Stack class given in the book in order for it to store do.pdffathimafancy
 
Let V be a finite dimensional vector space over F with T element (V,.pdf
Let V be a finite dimensional vector space over F with T element  (V,.pdfLet V be a finite dimensional vector space over F with T element  (V,.pdf
Let V be a finite dimensional vector space over F with T element (V,.pdffathimafancy
 
Java programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdfJava programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdffathimafancy
 
In the follwoing double bond hydration reaction styrene + water (so.pdf
In the follwoing double bond hydration reaction styrene + water (so.pdfIn the follwoing double bond hydration reaction styrene + water (so.pdf
In the follwoing double bond hydration reaction styrene + water (so.pdffathimafancy
 

More from fathimafancy (20)

Write the program segment necessary to Test the C flag. i. If the .pdf
Write the program segment necessary to  Test the C flag.  i. If the .pdfWrite the program segment necessary to  Test the C flag.  i. If the .pdf
Write the program segment necessary to Test the C flag. i. If the .pdf
 
Why must Group IV be treated with (NH4)2CO3 in basic solution What .pdf
Why must Group IV be treated with (NH4)2CO3 in basic solution What .pdfWhy must Group IV be treated with (NH4)2CO3 in basic solution What .pdf
Why must Group IV be treated with (NH4)2CO3 in basic solution What .pdf
 
what is IOT what us SolutionAns. IOT stands for Internet of Th.pdf
what is IOT what us SolutionAns. IOT stands for Internet of Th.pdfwhat is IOT what us SolutionAns. IOT stands for Internet of Th.pdf
what is IOT what us SolutionAns. IOT stands for Internet of Th.pdf
 
What is the difference between a BSS and a ESSSolutionBSS sta.pdf
What is the difference between a BSS and a ESSSolutionBSS sta.pdfWhat is the difference between a BSS and a ESSSolutionBSS sta.pdf
What is the difference between a BSS and a ESSSolutionBSS sta.pdf
 
What is the role of capsid and nucleocapsid proteins during the life.pdf
What is the role of capsid and nucleocapsid proteins during the life.pdfWhat is the role of capsid and nucleocapsid proteins during the life.pdf
What is the role of capsid and nucleocapsid proteins during the life.pdf
 
What distinguish between managerial and financial accounting as to (.pdf
What distinguish between managerial and financial accounting as to (.pdfWhat distinguish between managerial and financial accounting as to (.pdf
What distinguish between managerial and financial accounting as to (.pdf
 
There is a lack of spirituality in a person that cheats because they.pdf
There is a lack of spirituality in a person that cheats because they.pdfThere is a lack of spirituality in a person that cheats because they.pdf
There is a lack of spirituality in a person that cheats because they.pdf
 
select the answer a general search engine differs from a subject di.pdf
select the answer a general search engine differs from a subject di.pdfselect the answer a general search engine differs from a subject di.pdf
select the answer a general search engine differs from a subject di.pdf
 
State briefly what functions an Engineering Services Department in a.pdf
State briefly what functions an Engineering Services Department in a.pdfState briefly what functions an Engineering Services Department in a.pdf
State briefly what functions an Engineering Services Department in a.pdf
 
Satellites in geosynchronous orbit have the desirable property of re.pdf
Satellites in geosynchronous orbit have the desirable property of re.pdfSatellites in geosynchronous orbit have the desirable property of re.pdf
Satellites in geosynchronous orbit have the desirable property of re.pdf
 
Research and discuss an incident where it was discovered that a Remo.pdf
Research and discuss an incident where it was discovered that a Remo.pdfResearch and discuss an incident where it was discovered that a Remo.pdf
Research and discuss an incident where it was discovered that a Remo.pdf
 
Please review the attached casescenario. You are Bill. Feel free to.pdf
Please review the attached casescenario. You are Bill. Feel free to.pdfPlease review the attached casescenario. You are Bill. Feel free to.pdf
Please review the attached casescenario. You are Bill. Feel free to.pdf
 
Please make sure it works Ive been struggling with this and so far.pdf
Please make sure it works Ive been struggling with this and so far.pdfPlease make sure it works Ive been struggling with this and so far.pdf
Please make sure it works Ive been struggling with this and so far.pdf
 
Please explain the physiological mechanism for enlarged lymph nodes..pdf
Please explain the physiological mechanism for enlarged lymph nodes..pdfPlease explain the physiological mechanism for enlarged lymph nodes..pdf
Please explain the physiological mechanism for enlarged lymph nodes..pdf
 
multiple choiceAssuming that the probability for each shot is .pdf
multiple choiceAssuming that the probability for each shot is .pdfmultiple choiceAssuming that the probability for each shot is .pdf
multiple choiceAssuming that the probability for each shot is .pdf
 
Mathematical Statistics.....Could answer be typed (is there any link.pdf
Mathematical Statistics.....Could answer be typed (is there any link.pdfMathematical Statistics.....Could answer be typed (is there any link.pdf
Mathematical Statistics.....Could answer be typed (is there any link.pdf
 
Modify the Stack class given in the book in order for it to store do.pdf
Modify the Stack class given in the book in order for it to store do.pdfModify the Stack class given in the book in order for it to store do.pdf
Modify the Stack class given in the book in order for it to store do.pdf
 
Let V be a finite dimensional vector space over F with T element (V,.pdf
Let V be a finite dimensional vector space over F with T element  (V,.pdfLet V be a finite dimensional vector space over F with T element  (V,.pdf
Let V be a finite dimensional vector space over F with T element (V,.pdf
 
Java programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdfJava programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdf
 
In the follwoing double bond hydration reaction styrene + water (so.pdf
In the follwoing double bond hydration reaction styrene + water (so.pdfIn the follwoing double bond hydration reaction styrene + water (so.pdf
In the follwoing double bond hydration reaction styrene + water (so.pdf
 

Recently uploaded

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Recently uploaded (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

In this project you implement a program such that it simulates the p.pdf

  • 1. 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
  • 2. 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 Solution 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");
  • 3. ; 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! " + getReport(distance, range, velocity, angle, g);
  • 4. 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! " + 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())
  • 5. 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! " + 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);
  • 6. bestAngle = angle; } if (Math.abs(distance - range) < 1.0) { hit = true; } else { // Display report String outputText = "MISSED! " + getReport(distance, range, velocity, angle, g); System.out.println(outputText); JOptionPane.showMessageDialog(frame, outputText); } } String str = ""; if (hit) { str = "HIT!!! " + getReport(distance, getRange(velocity, g, bestAngle), velocity, angle, g); } else { str = "Best Attempt " + 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) + " "); str.append("Launch Velocity: " + String.format("%.2f", velocity) + " "); str.append("Launch Angle: " + String.format("%.2f", angle) + " "); str.append("Range: " + String.format("%.2f", range) + " "); str.append("Time of flight: " + String.format("%.2f", findTimeOfFlight(velocity, angle, g))
  • 7. + " "); str.append("Maximum height reached: " + String.format("%.2f", findMaximumHeight(velocity, angle, g)) + " "); 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; }
  • 8. }