Reputation: 4268
I have just started to learn groovy. I am executing the program below:-
class hello {
static void main(def args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
print "Input:"
int userInput = br.read()
println userInput
for(int i=1;i<10;i++)
{
int res = userInput + i
println "$res"
}
}
}
When i am entering any value it is giving strange value of userInput
. I tried clearing the project and re-execute it. Then i figured out that it is taking the first number and printing its ASCII value
. Why is it so ? Do i need to typecast ?
I even tried br.read().toInteger()
but doesn't work.
Upvotes: 0
Views: 61
Reputation: 171194
You're just reading the first char of the steam as an int ascii value.
Try reading the full line then converting it to an int:
int userInput = Integer.parseInt( br.readLine() )
More idiomatically, your class becomes (assuming Java 6):
class Hello {
static main( args ) {
System.console().with { c ->
int userInput = Integer.parseInt( c.readLine( 'Input : ' ) )
println userInput
(1..9).each {
println userInput + it
}
}
}
}
Upvotes: 2