logankilpatrick
logankilpatrick

Reputation: 14561

How to prompt a user for input until the input is valid in Julia

I am trying to make a program to prompt a user for input until they enter a number within a specific range.

What is the best approach to make sure the code does not error out when I enter a letter, a symbol, or a number outside of the specified range?

Upvotes: 3

Views: 392

Answers (2)

giordano
giordano

Reputation: 8344

In alternative to parse, you can use tryparse:

tryparse(type, str; base)

Like parse, but returns either a value of the requested type, or nothing if the string does not contain a valid number.

The advantage over parse is that you can have a cleaner error handling without resorting to try/catch, which would hide all exceptions raised within the block.

For example you can do:

while true
    print("Please enter a whole number between 1 and 5: ")
    input = readline(stdin)
    value = tryparse(Int, input)
    if value !== nothing && 1 <= value <= 5
        println("You entered $(input)")
        break
    else
        @warn "Enter a whole number between 1 and 5"
    end
end

Sample run:

Please enter a whole number between 1 and 5: 42
┌ Warning: Enter a whole number between 1 and 5
└ @ Main myscript.jl:9
Please enter a whole number between 1 and 5: abcde
┌ Warning: Enter a whole number between 1 and 5
└ @ Main myscript.jl:9
Please enter a whole number between 1 and 5: 3
You entered 3

Upvotes: 5

logankilpatrick
logankilpatrick

Reputation: 14561

This is one possible way to achieve this sort of thing:


while true
    print("Please enter a whole number between 1 and 5: ")
    input = readline(stdin)
    try
        if parse(Int, input) <= 5 || parse(Int, input) >= 1
            print("You entered $(input)")
            break
        end
    catch
        @warn "Enter a whole number between 1 and 5"
    end
end

Sample Run:

Please enter a whole number between 1 and 5: 2
You entered 2

See this link for how to parse the user input into an int.

Upvotes: 1

Related Questions