Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

java - Android: Cannot invoke toString() on the primitive type int

If I try

nltxt = nllen.toString();

with nllen being

int nllen = nl.getLength();

I get the error

Cannot invoke toString() on the primitive type int.

I want to convert the int to string so i can display the number of entries with Log... Why doesn't it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Primitives do not have any fields or methods. Sometimes the compiler will "autobox" your primitive into the corresponding class, Integer in this case. Perhaps that is what you expected in this case. Sometimes the compiler will not do this. In this case it does not automatically autobox it.

You have a few alternatives:

  1. String.valueOf(nltxt)

  2. "" + nltxt (or if you have something useful to write along with the number, do "nltxt equals " + nltxt

  3. Do the "autoboxing" manually: new Integer(nltxt).toString().

  4. Format it in some custom way: String.format("nltxt is %d which is bad%n", nltxt)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...