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?
daloo
March 26, 2018, 8:45pm
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.
1 Like
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.
swlkr
March 27, 2018, 3:02am
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 +