~/Lgroovy/overloading$ cat -n ComplexNumber.groovy 1 class MyComplex { 2 def real, imaginary 3 4 def plus(other) { 5 new MyComplex( 6 real: real+other.real, 7 imaginary: imaginary+other.imaginary 8 ) 9 } 10 11 String toString() { 12 "$real "+(imaginary > 0? "+${imaginary}i" : '') 13 } 14 15 def static _numre = /\s*([-+]?\d+(?:\.\d*)?)\s*/ 16 def static _complexre = ~/^\s*${_numre}\s*(?:\+\s*${_numre}i)?$/ 17 18 def static read() { 19 20 def scanner = new Scanner(System.in) 21 22 print "Enter a complex number (e.g. 2+1i): "; 23 def input = scanner.nextLine() 24 25 def m = (input =~ _complexre); 26 if (m) { 27 m = m[0] 28 def re = m[1].toDouble() 29 def im = m[2]? m[2].toDouble() : 0.0; 30 31 return new MyComplex(real : re, imaginary: im) 32 } 33 34 throw new Exception("\n\tExpected a complex number. Found: '$input'\n") 35 } 36 37 } 38 39 c1 = MyComplex.read() 40 c2 = MyComplex.read() 41 42 println c1+c2Ejecución:
~/Lgroovy/overloading$ groovy ComplexNumber.groovy Enter a complex number (e.g. 2+1i): 2+3i Enter a complex number (e.g. 2+1i): 4+5i 6.0 +8.0i ~/Lgroovy/overloading$ groovy ComplexNumber.groovy Enter a complex number (e.g. 2+1i): juf+plos i Caught: java.lang.Exception: Expected a complex number. Found: 'juf+plos i' at MyComplex.read(ComplexNumber.groovy:34) at ComplexNumber.run(ComplexNumber.groovy:39) ~/Lgroovy/overloading$ groovy ComplexNumber.groovy Enter a complex number (e.g. 2+1i): 2 Enter a complex number (e.g. 2+1i): 3 5.0 ~/Lgroovy/overloading$ groovy ComplexNumber.groovy Enter a complex number (e.g. 2+1i): 2+i Caught: java.lang.Exception: Expected a complex number. Found: '2+i' at MyComplex.read(ComplexNumber.groovy:34) at ComplexNumber.run(ComplexNumber.groovy:39)