Guess the number/With feedback: Difference between revisions

Added Groovy
(Added Groovy)
Line 1,070:
}
}</lang>
 
=={{header|Groovy}}==
Based on the Java implementation
<lang groovy>
def rand = new Random() // java.util.Random
def range = 1..100 // Range (inclusive)
def number = rand.nextInt(range.size()) + range.from // get a random number in the range
 
println "The number is in ${range.toString()}" // print the range
 
def guess
while (guess != number) { // keep running until correct guess
try {
print 'Guess the number: '
guess = System.in.newReader().readLine() as int // read the guess in as int
switch (guess) { // check the guess against number
case { it < number }: println 'Your guess is too low'; break
case { it > number }: println 'Your guess is too high'; break
default: println 'Your guess is spot on!'; break
}
} catch (NumberFormatException ignored) { // catches all input that is not a number
println 'Please enter a number!'
}
}
</lang>
Example:
<lang>
The number is in 1..100
Guess the number: ghfvkghj
Please enter a number!
Guess the number: 50
Your guess is too low
Guess the number: 75
Your guess is too low
Guess the number: 83
Your guess is too low
Guess the number: 90
Your guess is too low
Guess the number: 95
Your guess is too high
Guess the number: 92
Your guess is spot on!
</lang>
 
=={{header|Haskell}}==
Anonymous user