views:

41

answers:

5

Hello all,

I'm really brand new to Groovy and I'm trying to get something done. I've written some Groovy code (which works just fine) which receives some text. This text should be an integer (between 0 and 10). It may just happen a user enters something different. In that case I want to do some specific error handling.

Now I'm wondering, what's the best / grooviest way to test if a string-typed variable can be casted to an integer?

(what I want to do is either consume the integer in the string or set the outcome of my calculation to 0.

Thanks!

+3  A: 

The String class has a isInteger() method you could use:

def toInteger (String input) {
    if (input?.isInteger()) {
        return input.toInteger()
    }
    return 0
}
Christoph Metzendorf
Blacktiger
I'd suggest using a Groovy range to check if the value is between 0 and 10.Like:if(intValue in 0..10) { // do something }
xlson
A: 

Is this what you're saying?

  Integer integer = 0
  try {
    integer = (Integer) string
    assert integer > 0
    assert integer < 10
  catch(e) {
    integer = 0
  }
Chris Alef
A: 

There are lots of ways this can be done in groovy, if you're comfortable with regular expressions, this is about as concise as you can get:

def processText(String text) {
    text ==~ /(10|\d)/ ? text.toInteger() : 0
}

assert 0 == processText("-1")
(0..10).each { 
    assert it == processText("$it") 
}
assert 0 == processText("11")

I'm a little unsure what you mean by "specific error handling" if the user does something different.

If this is a web application, I'd take a look at grails and the constraints that you can put on the fields of a domain object, that would let you easily express what you're trying to do.

Ted Naleid
+1  A: 

use groovy contains

if ( x?.isInteger()) {
    return (0..10).contains(x) 
} else {
    return false
}
Aaron Saunders
A: 

You have the grails tag on your question, so if you are using Grails, you might consider making this an Integer property on a domain class. The param may come in as text, but you can bind it to an integer property with a default value of 0:

class MyDomain {
  Integer whatever = 0

  static constraints = {
    whatever( min:0, max:10)
  }
}
Javid Jamae