I need to modify the java program below so that it is a user defined method that
ID: 3823375 • Letter: I
Question
I need to modify the java program below so that it is a user defined method that does the following:
Write a method that accepts mass and a velocity as arguments/paraments. The method should calculate and return the kinetic energy.
In the main method, asks the user to enter values of mass and velocity, then calls the method to get the results and print them.
The user input should be validated. If the user inputs are invalid, outputs a error message.
The program should repeadetly accept the user input and calculate the result until the user chooses not to.
In the end, the average value should be calculated.
The results should be formatted appropriately.
Do not use global variables for this program!!!
import java.util.Scanner; //use a Scanner object to represent the keyboard
public class Energy
{
public static void main(String[] args)
{
//create the Scanner object representing the keyboard
Scanner console = new Scanner(System.in);
// declare variables
double mass;
double velocity;
double kinetic;
// User Information
System.out.print ("Enter the mass in Kilograms or -1 to end: ");
mass = console.nextDouble();
while (mass != -1)
{
System.out.print ("Enter the velocity in meters per second: ");
velocity = console.nextDouble();
kinetic = (0.5)*(mass)*(velocity)*(velocity);
// print the results
System.out.printf ("Your Kinetic Energy is %f ", kinetic);
}
}// end main
}// end class
Explanation / Answer
Energy.java
import java.util.Scanner; //use a Scanner object to represent the keyboard
public class Energy
{
public static void main(String[] args)
{
//create the Scanner object representing the keyboard
Scanner console = new Scanner(System.in);
// declare variables
double mass;
double velocity;
double kinetic;
// User Information
System.out.print ("Enter the mass in Kilograms or -1 to end: ");
mass = console.nextDouble();
while (mass != -1)
{
System.out.print ("Enter the velocity in meters per second: ");
velocity = console.nextDouble();
kinetic = getKineticEnergy(velocity, mass);
// print the results
System.out.printf ("Your Kinetic Energy is %f ", kinetic);
System.out.print ("Enter the mass in Kilograms or -1 to end: ");
mass = console.nextDouble();
}
}// end main
public static double getKineticEnergy(double velocity, double mass){
return (0.5)*(mass)*(velocity)*(velocity);
}
}// end class
Output:
Enter the mass in Kilograms or -1 to end: 100
Enter the velocity in meters per second: 5
Your Kinetic Energy is 1250.000000
Enter the mass in Kilograms or -1 to end: 50
Enter the velocity in meters per second: 5
Your Kinetic Energy is 625.000000
Enter the mass in Kilograms or -1 to end: -1