Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take user input and insert it into an array?

Tags:

julia

New to Julia, trying to simply ask the user to choose 5 numbers and put it into an array and print the array. My output only says pick 5 numbers with "nothing" followed underneath. I cant seem to figure out why it wont read my inputs.

function ask()
   lst = []
   i = 0
   println("pick 5 numbers to add to a list")
   while i < 5
     choice = readline
     choice = push!(lst, choice);
     i += 1
    end 
end
 
println(ask())

like image 978
D_D Avatar asked Oct 28 '25 14:10

D_D


1 Answers

You were assigning function reference to list elements rather than calling the function.

This should be:

function ask()
   lst = String[]
   i = 0
   println("pick 5 numbers to add to a list")
   while i < 5
     choice = readline()
     choice = push!(lst, choice);
     i += 1
   end 
   lst
end

If you want numbers rather than Strings the last line could be parse.(Int, lst) or you could add this conversion near readline

Note that if you do not plan to introduce some error checking etc. this all code could be simply written as:

println("pick 5 numbers to add to a list")
lst = [parse(Int, readline()) for _ in 1:5]
like image 137
Przemyslaw Szufel Avatar answered Oct 31 '25 13:10

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!