Incomprehensible result of an if statement


#1

Hey, I try to write some clojure scripts. I want the user to enter two numbers and than the program does arithmetical stuff. But something wents wrong.

(print "enter a number: ")
(flush)(def number1 (read-line))
(print "enter a second number: ")
(flush) (def number2 (read-line)) 
(newline)

(println "[1] sum up")
(println "[2] substract")
(println "[3] multiplicate")
(println "[4] divide")
(print "input: ")
(flush) (def operation (read-line)) 

(if (= operation 1) (
  (print "solution:" )
  (print (+ number1 number2))
) (println "Something went wrong"))

He prints out “Something went wrong” if you enter 1. Why?


#2

Hi, the read-line function returns a string variable. You compare the operation value with an integer value (1).Compare to “1” should work.
The next problem is that you try to use the + function with string variables. Use of Integer/parseInt function should help for this one.


#3

Also, you need a do block inside the success branch of your if.

If you need more help, please ask! Slack has a dedicated beginners and programming-beginners channel where you may get faster feedback.


#4

I had to reformat the text a little bit to make sure I knew what was going on, but here’s what I think you wanted to do.

(do
  (print "enter a number: ")
  (flush)
  (def number1 (read-line))

  (print "enter a second number: ")
  (flush)
  (def number2 (read-line))

  (newline)

  (println "[1] sum up")
  (println "[2] substract")
  (println "[3] multiplicate")
  (println "[4] divide")
  (print "input: ")
  (flush)
  (def operation (read-line))

  (if (= operation "1")
    (do
      (print "solution:")
      (println (+ (Integer/parseInt number1) (Integer/parseInt number2))))
    (println "Something went wrong")))

Everything from read-line comes in as a string, you have to convert to the right type to call +


#5