How to resolve the algorithm Guess the number/With feedback step by step in the Groovy programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Guess the number/With feedback step by step in the Groovy programming language
Table of Contents
Problem Statement
Write a game (computer program) that follows the following rules:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Guess the number/With feedback step by step in the Groovy programming language
Source code in the groovy programming language
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!'
}
}
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!
You may also check:How to resolve the algorithm O'Halloran numbers step by step in the J programming language
You may also check:How to resolve the algorithm Queue/Usage step by step in the Raku programming language
You may also check:How to resolve the algorithm Longest common substring step by step in the Haskell programming language
You may also check:How to resolve the algorithm Gauss-Jordan matrix inversion step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm Kernighans large earthquake problem step by step in the Action! programming language