53 lines
1.4 KiB
Groovy
53 lines
1.4 KiB
Groovy
class Calculator {
|
|
def add(int a, int b) {
|
|
return a + b
|
|
}
|
|
|
|
def subtract(int a, int b) {
|
|
return a - b
|
|
}
|
|
|
|
def multiply(int a, int b) {
|
|
return a * b
|
|
}
|
|
|
|
def divide(int a, int b) {
|
|
if (b == 0) {
|
|
println("Error: Division by zero!")
|
|
return
|
|
}
|
|
return a / b
|
|
}
|
|
|
|
def performOperation(int a, int b, Closure operation) {
|
|
return operation(a, b)
|
|
}
|
|
}
|
|
|
|
// Verwendung der Klasse Calculator
|
|
def calc = new Calculator()
|
|
|
|
// Grundrechenoperationen
|
|
println("Addition: ${calc.add(5, 3)}")
|
|
println("Subtraktion: ${calc.subtract(10, 7)}")
|
|
println("Multiplikation: ${calc.multiply(4, 6)}")
|
|
println("Division: ${calc.divide(12, 4)}")
|
|
|
|
// Closures definieren
|
|
def addClosure = { int a, int b -> a + b }
|
|
def subtractClosure = { int a, int b -> a - b }
|
|
def multiplyClosure = { int a, int b -> a * b }
|
|
def divideClosure = { int a, int b ->
|
|
if (b == 0) {
|
|
println("Error: Division by zero!")
|
|
return
|
|
}
|
|
return a / b
|
|
}
|
|
|
|
// Verwendung von performOperation mit Closures
|
|
println("Addition mit Closure: ${calc.performOperation(5, 3, addClosure)}")
|
|
println("Subtraktion mit Closure: ${calc.performOperation(10, 7, subtractClosure)}")
|
|
println("Multiplikation mit Closure: ${calc.performOperation(4, 6, multiplyClosure)}")
|
|
println("Division mit Closure: ${calc.performOperation(12, 4, divideClosure)}")
|