```java
class ComplexJ {
public double real, imag;
// Constructor
public ComplexJ(double r, double i) {
real = r; imag = i;
}
// Add other Complex and return new
public ComplexJ add(ComplexJ other) {
return new ComplexJ(real + other.real,
imag + other.imag);
}
}
class ComplexJRunner {
public static void main(String args[]) {
// add random complex numbers
ComplexJ x = new ComplexJ(0, 0);
for (int r = 1; r <= 3; r++) {
double i = Math.random() * 5;
x = x.add(new ComplexJ(r, i));
}
System.out.println("Result: " +
"(" + x.real + "+" + x.imag + "i)");
}
}
```
|
```scala
class ComplexS(var real: Double,
var imag: Double) {
// Add other Complex and return new
def add(other: ComplexS) = { // (1)
new ComplexS(real + other.real, // (2)
imag + other.imag)
}
}
object ComplexSRunner {
def main(args: Array[String]) = {
// add random complex numbers
var x = new ComplexS(0, 0)
for (r <- 1 to 3) {
var i = Math.random * 5 // (3)
x = x add new ComplexS(r, i) // (4)
}
println("Result: " +
"(" + x.real + "+" + x.imag + "i)")
}
}
```
- Drop semicolons (yay!)
- Use type inference
- Omit `return`, use last statement instead
- Drop brackets for no-argument methods
- Drop brackets and dot for one-argument methods
|