Best way to search a string and return a conditional output in Julia?

Viewed 48

I am trying to write a simple BMI calculator in Julia using visual studio code. I want the program to first ask the user whether they prefer "metric" or "imperial" units, then tailor the follow-on questions based on the user's answer. Any suggestions on the best way to structure this? For example, I've tried:

println("Welcome, what is your name?")
user_name = readline(stdin)
println("Hello $user_name, nice to meet you.")

println("Please choose whether you would like to use metric or imperial units:"
preferred_units = readline(stdin)
function preference()
    if startswith(preferred_units, "imperial")
    println("Enter your weight in lbs:")
    weight_imperial = parse(Float64, deadline(stdin))
else
    if startswith(preferred_units, "metric")
    println("Enter your weight in kg:")
    weight_metric = parse(Float64, deadline(stdin))
end

Is there a different function that would be more appropriate here?

1 Answers

Your code errors for me because of a couple tiny typos/mistakes. This works for me:

println("Welcome, what is your name?")
user_name = readline(stdin)
println("Hello $user_name, nice to meet you.")

println("Please choose whether you would like to use metric or imperial units:")
preferred_units = readline(stdin)
function preference()
    if startswith(preferred_units, "imperial")
        println("Enter your weight in lbs:")
        weight_imperial = parse(Float64, readline(stdin))
    elseif startswith(preferred_units, "metric")
        println("Enter your weight in kg:")
        weight_metric = parse(Float64, readline(stdin))
    end 
end
preference()
Related