Search code examples
javamathoutputjava.util.scannerexponent

Trying to output solution to math equation always results in 0


I am a complete beginner with java and coding altogether and am trying to make a program that solves two equations based on what a user has inputted into the program. I've tried changing the variable types to long, int, double, but nothing changes. The result is always 0 or 0.0 Any help would be much appreciated.

package pa2;
import java.util.Scanner;
public class GravitationalForce 
{
    public static void main(String[] args) 

        {
            System.out.println("Please enter the name of the planet and its weight in quintillion kilograms");
            Scanner myScanner = new Scanner (System.in);
            String planetName = myScanner.next();
            int planetWeight = myScanner.nextInt();

            System.out.println("Enter the weight of the person in kilograms");
            double personWeight = myScanner.nextDouble();

            System.out.println("Please enter the radius of the planet Alderaan in million meters");
            double planetRadius = myScanner.nextDouble();
            Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
            Double force = gravitationalConstant*(planetWeight*Math.pow(10, 18)*personWeight)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6);
            Double gravity = gravitationalConstant*(planetWeight*Math.pow(10, 18)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6));

            System.out.println("The gravitational force of planet " + planetName + " on the person is " + force + " Newtons");
            System.out.println("The gravity of the planet " + planetName + " is " + gravity + " meters per second squared");
        }
}

Solution

  • 6.673*Math.pow(10,-11) is < 1, so if you cast it to long, it becomes 0.

    change

    Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
    

    to

    double gravitationalConstant = 6.673*Math.pow(10,-11);