Mass and weight

The problem

Scientists measure an object’s mass in kilograms and its weight in Newtons. If you know the amount of mass that an object has, you can calculate its weight, in Newtons, with the following formula:

  • Weight = mass X 9.8

Write a program that asks the user to enter an object’s mass, and then calculate its weight. If the object weighs more than 1000 Newtons, display a message indicating that it is too heavy. If the object weighs less than 10 Newtons, display a message indicating that the object is too light.

Breaking it down

public static void main(String[] args) {

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(;

    // Describe to the user what the program will do.
    System.out.println("Enter the object's mass:");

    double mass = keyboard.nextDouble();

    //close scanner

    // pass mass to calculate weight
    double weight = calculateWeightInNewtons(mass);

    System.out.println("The object's weight is: " + weight);

    // get message per requirement
    String message = validWeight(weight);

    if (message.length() > 0) {


Enter the object's mass:
The object's weight is: 196000.0
The object is to heavy

Unit tests

public void test_validWeight_lt10() {

    String message = MassAndWeight.validWeight(9);

    assertEquals("The object is to light", message);

public void test_validWeight_gt1000() {

    String message = MassAndWeight.validWeight(1001);

    assertEquals("The object is to heavy", message);

public void test_validWeight() {

    String message = MassAndWeight.validWeight(500);

    assertEquals("", message);

public void test_calculateWeightInNewtons() {

    double weight = MassAndWeight.calculateWeightInNewtons(100);

    assertEquals(980.0000000000001, weight, 0);

Level Up

  • Format weight to the 2 decimal place