开发者

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 t开发者_如何学编程ype int.

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


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)


Primitive types aren't objects and as such don't have any methods.

To convert it to a String use String.valueOf(nlTxt).


You could also use Integer.toString(nllen); for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜