Search⌘ K
AI Features

Solution: Planetary Gravity Calculator

Explore the application of variables, type inference using var, and type casting in Java by solving a planetary gravity calculator. Learn how to handle double precision, perform arithmetic operations, and convert results for display.

We'll cover the following...
Java 25
public class MarsWeightCalculator {
public static void main(String[] args) {
// 1. Use var for type inference
var earthGravity = 9.81;
var marsGravity = 3.73;
var earthWeight = 85.5;
// 2. Calculate precise floating-point result
// Formula: Weight * (MarsG / EarthG)
double preciseMarsWeight = earthWeight * (marsGravity / earthGravity);
// 3. Perform explicit narrowing cast
// This drops the decimal part completely
int displayWeight = (int) preciseMarsWeight;
// 4. Output results
System.out.println("Scientific Log: " + preciseMarsWeight);
System.out.println("Cockpit Display: " + displayWeight);
}
}
...