Pansophical T
Pansophical T

Reputation: 5

Comparitive operator not working in Julia script file when used in control flow with conditional operator

I have tried different operators <,>,etc. Nothing seems to work when I combine comparative operators with conditional operators.

e = readline()

if e == 0
    println("e is equal to 0")
else
        println("e is not equal to 0")
end

The expected result is obvious, if e = 0, prints e is equal to 0, if e != 0, prints e is not equal to 0.

However, it always prints the bottom line, e is not equal to 0.

Upvotes: 0

Views: 43

Answers (2)

Antonello
Antonello

Reputation: 6431

The reason that the if returns the branch that you don't expect is those given to you by @phg (you got a String by readline()).

For my code I use the following function to parse user-provided data given in a terminal:

function getUserInput(T=String,msg="")
  print("$msg ")
  if T == String
      return readline()
  else
    try
      return parse(T,readline())
    catch
     println("Sorry, I could not interpret your answer. Please try again")
     getUserInput(T,msg)
    end
  end
end

sentence = getUserInput(String,"Which sentence do you want to be repeated?");
n        = getUserInput(Int64,"How many times do you want it to be repeated?");
[println(sentence) for i in 1:n]
println("Done!")

Upvotes: 0

phipsgabler
phipsgabler

Reputation: 20950

That's because readline returns a string, which is never equal to an integer (by the definition of == Julia uses).

Here are some possible ways to achieve what you want:

  • Compare to a string literal instead: if e == "0"
  • Use tryparse: if tryparse(Int, e) == 0 (will return nothing if e is not a number literal)
  • Use parse, but with try/catch instead of an if:
    try
        p = parse(Int, e)
        p == 0 ? println("e is 0") : println("e is not 0")
    catch
        println("not even an integer.")
    end
    

Upvotes: 2

Related Questions