r/Clojure • u/god_gamer_9001 • Jun 15 '25
Help Very large error message when attempting to use read-line variable in dotimes loop
Hello! I am very new to Clojure, and am trying to make a program that takes user input (in my case, through read-line), and uses it in a dotimes loop. This is my code thus far:
(ns clojure.examples.hello
(:gen-class))
(defn Example []
(println "Number: ")
(def x (read-string (read-line)))
(dotimes [i num]
(println i)))
(Example)However, when I try to run it, I get this error message:
class clojure.core$num cannot be cast to class java.lang.Number (clojure.core$num is in unnamed module of loader 'app'; java.lang.Number is in module java.base of loader 'bootstrap')Why is this? What have I done wrong? My guess is that I've done something fundamentally wrong with the dotimes loop, or the value outputted by (read-string (read-line)) isn't compatible with a dotimes loop, but I'm not sure. Any and all help would be appreciated.
10
Upvotes
3
u/birdspider Jun 15 '25
since you do not declare a new
num, clojure thinks you are talking aboutclojure.core/num(a function), hence a loop loopingnumtimes makes no sense3
u/HotSpringsCapybara Jun 15 '25
Adding to answers you were already given: use
let, rather thandeffor local bindings. I also recommend that you visit clojuredocs.org as your go-to for documentation. It features extremely useful comments and examples.I assume this is what you were trying to do:
4
u/npafitis Jun 15 '25
birdspider already answered your question, but you are not supposed to use def inside of a defn. Def and defn are supposed to be top level only
1
u/deaddyfreddy Jun 17 '25
Most likely, your editor/IDE has clj-kondo support. And if it doesn't, I'd recommend replacing it with a proper one. It can easily detect such errors.