Scala Program: MathConstants object with PI and E constants
Scala OOP Exercise-11 with Solution
Write a Scala program that creates an object MathConstants with constants for mathematical calculations such as PI and E.
Sample Solution:
Scala Code:
object MathConstants {
val PI: Double = 3.14159
val E: Double = 2.71828
}
object MathConstantsApp {
def main(args: Array[String]): Unit = {
println(s"The value of PI is: ${MathConstants.PI}")
println(s"The value of E is: ${MathConstants.E}")
}
}
Sample Output:
The value of PI is: 3.14159 The value of E is: 2.71828
Explanation:
In the above exercise, the "MathConstants" object is defined with two properties 'PI' and 'E'. These properties are defined as val and assigned the corresponding constant values.
The "MathConstantsApp" object contains the "main()" method where we can test functionality. It simply prints the values of 'PI' and 'E' using the "MathConstants" object.
Scala Code Editor :
Previous: Resizable Trait with rectangle class implementation.
Next: Destructuring declarations in point class.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/oop/scala-oop-exercise-11.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics