我试图通过编写经典猜谜编号游戏来学习朱莉娅:
function main()
secret_number = rand(1:10)
println("Guess my number! ")
guess_number =
try
int(chomp(readline(STDIN)))
catch ex
println("Invalid number. Please enter a number:")
# how to continue here?
int(chomp(readline(STDIN)))
end
while(guess_number != secret_number)
validate(guess_number, secret_number)
guess_number = int(chomp(readline(STDIN)))
end
println("You win!")
end
function validate(g_num,s_num)
if g_num < s_num
println("Too small!")
elseif g_num > s_num
println("Too big!")
else
println("Equal")
end
end
此程序只能处理来自输入的异常(即,如果用户输入不是数字),只能处理一次。第二次用户输入无效数字时,程序停止。如何处理在Julia中解析int
?
答案 0 :(得分:0)
验证循环内的第二个循环验证guess_number
实际上是一个数字可以解决这个问题,例如:
function main()
secret_number = rand(1:10)
println("Guess my number! ")
guess_number = 0
while(guess_number != secret_number)
valid = false
response = ""
while (!valid)
guess_number =
try
valid = true
response = chomp(readline(STDIN))
int(response)
catch ex
if (response == "q")
return
end
println("Invalid number. Please enter a number:")
valid = false
end
end
validate(guess_number, secret_number)
end
println("You win!")
end
function validate(g_num,s_num)
if g_num < s_num
println("Too small!")
elseif g_num > s_num
println("Too big!")
else
println("Equal")
end
end
main()
这种方法也适用Don't repeat yourself (DRY)原则,只在一行中获得输入,而不是原始代码中的两行。
(编辑)
根据评论中的要求,我还提到了一种在被要求提供号码时输入“q”来退出main()
功能的方法。