如何提示用户输入,直到输入在Julia中有效

如何提示用户输入,直到输入在Julia中有效,julia,Julia,我试图制作一个程序来提示用户输入,直到他们输入特定范围内的数字 当我输入超出指定范围的字母、符号或数字时,确保代码不会出错的最佳方法是什么 这是实现这类目标的一种可能方式: while true print("Please enter a whole number between 1 and 5: ") input = readline(stdin) try if parse(Int, input) <= 5 || parse(Int, input

我试图制作一个程序来提示用户输入,直到他们输入特定范围内的数字


当我输入超出指定范围的字母、符号或数字时,确保代码不会出错的最佳方法是什么

这是实现这类目标的一种可能方式:


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

作为替代,您可以使用:

tryparse(type,str;base)

与解析类似,但返回请求类型的值,或
nothing
如果字符串不包含有效数字

与parse相比,它的优点是,您可以在不诉诸于的情况下进行更干净的错误处理,这将隐藏块中引发的所有异常

例如,您可以执行以下操作:

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

令人惊叹的!谢谢你指出这一点。如果您认为它看起来更简单,请随时发布替代解决方案。
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
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