Its Andrew
Its Andrew

Reputation: 155

Java - calculating the acceleration of gravity

I am currently working through problem sets for java and I am tasked with computing the acceleration of gravity however I am unsure as to get the appropriate result. The question is below:

Compute the acceleration of gravity for a given distance from the earth's center, distCenter, assigning the result to accelGravity. The expression for the acceleration of gravity is: (G * M) / (d2), where G is the gravitational constant 6.673 x 10-11, M is the mass of the earth 5.98 x 1024 (in kg) and d is the distance in meters from the earth's center (stored in variable distCenter).

Here is the code that was given to me:

import java.util.Scanner;
public class GravityCalculation {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      double G = 6.673e-11;
      double M = 5.98e24;
      double accelGravity;
      double distCenter;

      distCenter = scnr.nextDouble();

      // your code here

      System.out.println(accelGravity);
   }
}

I only have access to adjust what is below the // your code here.

I have translated the scientific notation of the numbers as necessary for the formula:

accelGravity = (0.00000000006673 * 5980000000000000000000000) / (distCenter * distCenter);

I am receiving the following error:

error: integer number too large

The problem set doesn't give me too much more information and I am well aware that the number translated to scientific is far too large for an int and even a long. I am not asking for someone to solve this for me, but rather point me in a direction where I can learn how to appropriately solve for problems like this.

Upvotes: 0

Views: 6650

Answers (1)

Kawser Habib
Kawser Habib

Reputation: 1422

Double can handle this range without any issue. I have modified your code. It gave me the correct result. When taking input, avoid any "," e.g.: 6371000 is valid input, 63,71000 is not valid.

5980000000000000000000000 is an integer, which is out of integer range, so you should use M instead of 5980000000000000000000000 Or use 5980000000000000000000000.00(add decimal part)

import java.util.Scanner;

public class GravityCalculation {
    
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      double G = 6.673e-11;
      double M = 5.98e24;
      double accelGravity;
      double distCenter = 6371000;

      System.out.print("Distance from center(default 6371000m): ");
      distCenter = scanner.nextDouble();

      // your code here
      accelGravity = (G * M) / (distCenter * distCenter);

      System.out.println("Gravity: " + accelGravity);
   }
}

Upvotes: 2

Related Questions