0

I need to input a number using read-line:

(def x (read-line))
user => 1

gives the error:

CompilerException java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number

1 Answer 1

3

That code alone won't cause that error.

read-line returns a String, and I'm guessing you're trying to use x in the context where a number is expected.

To reproduce the error, you could do:

(def x (read-line)) ; Enter 1
(+ 1 x) ; Same as (+ 1 "1"), which should make the problem obvious

ClassCastException java.lang.String cannot be cast to java.lang.Number  clojure.lang.Numbers.add (Numbers.java:128)

Change it to use Long/parseLong (or a similar function):

(def x (Long/parseLong (read-line)))

You need to parse x as a number (Long in this case) before it can be used as a number.

(def x (Long/parseLong (read-line)))
(+ 1 x)

=> 2

Of course though, Long/parseLong will throw if you try to have it parse something that can't be represented as a number. In the real world, you'll want to do proper error handling via try.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.