1

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");
        }
}
Nithin
  • 682
  • 1
  • 9
  • 24
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Ravi Feb 04 '18 at 06:37
  • @Ravi Why would that be? Code doesn't call `nextLine()`. – Andreas Feb 04 '18 at 07:11
  • You need to re-check your operator precedences. `a * b / c * d` is the same as `((a * b) / c) * d`, not the same as `(a * b) / (c * d)`, so `gravitationalConstant*(planetWeight*Math.pow(10, 18)*personWeight)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6)` is actually `gravitationalConstant * planetWeight * personWeight * planetRadius * Math.pow(10, 30) / planetRadius` – Andreas Feb 04 '18 at 07:14
  • 2
    `Math.pow(10, 18)` is better written as the `double` literal `1e18`. – Andreas Feb 04 '18 at 07:17

1 Answers1

3

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);
Eran
  • 359,724
  • 45
  • 626
  • 694