009-002-012

Encapsulation Design Pattern

Hard

Problem Description

Encapsulation Design Pattern

In this problem, you will create a program that defines a Temperature class with a validated setter setCelsius() that rejects out-of-range values, and a toFahrenheit() method that converts Celsius to Fahrenheit, then displays the results to standard output.

Learning Objective: Understand practical encapsulation design using private/public with getters/setters

Overview

Encapsulation makes fields private and controls external access through getters and setters. Setters perform validation to prevent invalid values from being set.

Specifications

  • Define a Temperature class
    • Private field: celsius (managed as int, not double)
    • Setter: setCelsius(int c) - range is -273 to 1000. Out-of-range values are ignored
    • Getter: getCelsius() - returns current temperature
    • toFahrenheit() - converts to Fahrenheit (celsius * 9 / 5 + 32)
  • Read three integer values from standard input
    • Line 1: initial temperature (valid range)
    • Line 2: temperature to attempt (out-of-range value)
    • Line 3: second temperature to set (valid range)
  • Test with valid values and out-of-range values

Input Format

<initial temperature>
<temperature to attempt (out of range)>
<second temperature>

Output Format

Celsius: <initial temperature>
Fahrenheit: <initial temperature in Fahrenheit>
Celsius: <temperature after attempt (unchanged)>
Celsius: <second temperature>
Fahrenheit: <second temperature in Fahrenheit>

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up