Java Android:无法在原始类型 int 上调用 toString()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3028974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: Cannot invoke toString() on the primitive type int
提问by R0b0tn1k
If I try
如果我尝试
nltxt = nllen.toString();
with nllen
being
与nllen
存在
int nllen = nl.getLength();
I get the error
我收到错误
Cannot invoke
toString()
on the primitive type int.
无法调用
toString()
原始类型 int。
I want to convert the int to string so i can display the number of entries with Log... Why doesn't it work?
我想将 int 转换为字符串,以便我可以使用 Log 显示条目数...为什么它不起作用?
回答by Chris
Primitive types aren't objects and as such don't have any methods.
原始类型不是对象,因此没有任何方法。
To convert it to a String use String.valueOf(nlTxt)
.
要将其转换为字符串,请使用String.valueOf(nlTxt)
.
回答by aioobe
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.
原语没有任何字段或方法。Integer
在这种情况下,有时编译器会将您的原语“自动装箱”到相应的类中。也许这就是您在这种情况下所期望的。有时编译器不会这样做。在这种情况下,它不会自动自动装箱。
You have a few alternatives:
你有几个选择:
String.valueOf(nltxt)
"" + nltxt
(or if you have something useful to write along with the number, do"nltxt equals " + nltxt
Do the "autoboxing" manually:
new Integer(nltxt).toString()
.Format it in some custom way:
String.format("nltxt is %d which is bad%n", nltxt)
String.valueOf(nltxt)
"" + nltxt
(或者如果你有一些有用的东西可以和数字一起写,做"nltxt equals " + nltxt
手动执行“自动装箱”:
new Integer(nltxt).toString()
。以某种自定义方式对其进行格式化:
String.format("nltxt is %d which is bad%n", nltxt)
回答by source.rar
You could also use Integer.toString(nllen);
for this.
您也可以Integer.toString(nllen);
为此使用。