Search⌘ K
AI Features

Solution: Planetary Gravity Calculator

Explore how to implement a planetary gravity calculator in Java by declaring variables with type inference, applying formulas with floating-point math, and converting results with type casting. Understand how to manipulate data types, perform narrowing conversions, and format outputs for clear display in this practical lesson.

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);
}
}
...