Recap - Simple Calculator
Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 8 of 65.
Challenge
MediumWrite the class Calculator in calculator.gd. It keeps a running result in the float property result, which starts at 0.0.
add(number),subtract(number),multiply(number)anddivide(number)apply the operation toresultwithnumber, store the new result and return it- When
divide()gets0, it printsError: Division by zero, leavesresultunchanged and returns it clear()setsresultback to0.0and returns itget_result()returnsresult
The supplied code reads how many commands follow, then one command per line, such as add 5, divide 0 or clear. After each command it prints the command name and the value the method returned, and at the end the final result. For add 5, multiply 3, subtract 2, divide 0 and divide 2 it prints:
add -> 5.0
multiply -> 15.0
subtract -> 13.0
Error: Division by zero
divide -> 13.0
divide -> 6.5
Final result: 6.5Your code goes in calculator.gd. main.gd holds the supplied input/output code and cannot be edited.
Try it yourself
extends Node
func _ready():
# Supplied input/output code: keep it as it is
var calc := Calculator.new()
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
var value := 0.0
match parts[0]:
"add":
value = calc.add(float(parts[1]))
"subtract":
value = calc.subtract(float(parts[1]))
"multiply":
value = calc.multiply(float(parts[1]))
"divide":
value = calc.divide(float(parts[1]))
"clear":
value = calc.clear()
print("%s -> %s" % [parts[0], value])
print("Final result: %s" % calc.get_result())
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self KeywordMethodsPropertiesConstructor (_init)Recap - Simple Calculator4Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator2Class Properties
Instance vs Static VariablesStatic FunctionsProperty SettersProperty GettersPrivate by ConventionRecap - Bank Account Manager5Encapsulation
Public and Private MembersValidation with SettersInformation HidingRead-Only PropertiesRecap - Student Records System8Advanced OOP Concepts
Composition vs InheritanceInner ClassesNodes as ComponentsRefCounted vs NodeEnums in Classes11Project: Library Management
Project OverviewBook and User Classes3Inheritance
Basic InheritanceThe super KeywordMethod OverridingInheritance ChainsType Checks with isRecap - Employee Hierarchy6Special Methods
Virtual Methods IntroductionThe _to_string MethodCustom IteratorsRecap - Custom List9Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy PatternPractice on your own: Online GDScript compiler