r/programminghelp • • Jan 15 '21

Java JAVA- KINETIC ENERGY

Hello experts and fellow learns, I'm stuck with this problem for a while and utilize all resources that I have for this activity but I can't seem to get it right. This is also a self study as Im not able to understand the lesson from our class due to poor internet connection, I need to call a function to get the object's kinetic energy. I appreciate your suggestions, tips, and helps etc. Thanks in advance.

This is my code:

import java.util.Scanner;

public class MyClass {

public static void main(String args[]) {

Scanner input = new Scanner(System.in);

double KE, m, v, ObjectKE;

System.out.print("Enter mass in kilograms:");

m = input.nextDouble();

System.out.print("Enter velocity in meters per second:");

v = input.nextDouble();

System.out.print("The object's kinetic energy is:");

KE= input.nextDouble();

System.out.print("The object's kinetic energy is: " + ObjectKE + "J");

}

public static double KineticEnergy (double m , double v){

double ObjectKE = (m * (0.5) * (Math.pow(v,2)));

return ObjectKE;

}

}

Result:/MyClass.java:12: error: variable ObjectKE might not have been initialized

System.out.print("The object's kinetic energy is: " + ObjectKE + "J");

^

1 error

4 Upvotes

6 comments sorted by

View all comments

Show parent comments

1

u/marko312 Jan 15 '21

What exactly would you like explained? Did you get this working or do you still need help with fixing this code?

1

u/anzsrouxjoyeuse Jan 15 '21

To be honest, I still need help with fixing this code but I'm really trying my best to figure it out it just that it takes me a moment and that somehow frustrated me

2

u/marko312 Jan 15 '21

OK. The code you posted prompts for and reads in the variables m, v and KE (although I don't really see the need for that last one).

It seems that you want to calculate the kinetic energy using the function KineticEnergy and store it in the variable ObjectKE in main (which is not directly related to the variable with the same name in KineticEnergy). To do this, you can call the function, passing in the parameters (m and v), and then capture the value returned from that function.

So, after m and v have both been read in, but before you print ObjectKE, you should add the line

ObjectKE = KineticEnergy(m, v);

which calls the function and captures the value returned from it in the variable ObjectKE.

2

u/anzsrouxjoyeuse Jan 15 '21

Thank you so much. I really appreciate it. I gonna keep going and solve that. Thanks again