Calculator with Method Chaining - Problem

Design a Calculator class that provides mathematical operations with method chaining support. The class should allow consecutive operations to be performed in a fluent interface style.

The Calculator constructor accepts an initial number which serves as the starting value for calculations.

Required Methods:

  • add(value) - Adds the given number to the result and returns the Calculator instance
  • subtract(value) - Subtracts the given number from the result and returns the Calculator instance
  • multiply(value) - Multiplies the result by the given number and returns the Calculator instance
  • divide(value) - Divides the result by the given number and returns the Calculator instance. Throws error "Division by zero is not allowed" if value is 0
  • power(value) - Raises the result to the power of the given number and returns the Calculator instance
  • getResult() - Returns the current result as a number

Solutions within 10⁻⁵ of the actual result are considered correct.

Input & Output

Example 1 — Basic Chaining
$ Input: Calculator(10).add(5).multiply(2).getResult()
Output: 30
💡 Note: Start with 10, add 5 to get 15, multiply by 2 to get 30
Example 2 — Power Operation
$ Input: Calculator(2).power(3).subtract(3).getResult()
Output: 5
💡 Note: Start with 2, raise to power 3 to get 8, subtract 3 to get 5
Example 3 — Division Error
$ Input: Calculator(10).divide(0)
Output: Error: Division by zero is not allowed
💡 Note: Division by zero throws an error as specified

Constraints

  • -1000 ≤ initial value ≤ 1000
  • -100 ≤ operation values ≤ 100
  • 1 ≤ number of operations ≤ 10
  • Division by zero throws error

Visualization

Tap to expand
Calculator with Method Chaining INPUT Calculator(10) Initial Value: 10 .add(5) .multiply(2) .getResult() Method Chain: Calculator(10) .add(5) .multiply(2) .getResult() ALGORITHM STEPS 1 Initialize this.result = 10 2 add(5) result = 10 + 5 = 15 3 multiply(2) result = 15 * 2 = 30 4 getResult() Return 30 Fluent Interface Pattern add(value) { this.result += value; return this; // enables // method chaining } Each method returns 'this' FINAL RESULT Calculator State result: 30 Output: 30 OK - Correct! Execution Trace 10 (initial) --> 10 add(5) --> 15 multiply(2) --> 30 getResult() --> 30 Key Insight: The Fluent Interface Pattern allows method chaining by returning 'this' from each method. This creates readable, expressive code: Calculator(10).add(5).multiply(2) reads like a sentence. Each operation modifies internal state and returns the object for the next operation in the chain. TutorialsPoint - Calculator with Method Chaining | Fluent Interface Pattern
Asked in
Google 25 Amazon 18 Microsoft 15
24.1K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen