【问题标题】:Android: Cannot invoke toString() on the primitive type intAndroid:无法在原始类型 int 上调用 toString()
【发布时间】:2023-03-17 05:50:01
【问题描述】:

如果我尝试

nltxt = nllen.toString();

nllen 存在

int nllen = nl.getLength();

我得到了错误

无法在原始类型 int 上调用 toString()

我想将 int 转换为字符串,以便我可以使用 Log 显示条目数... 为什么它不起作用?

【问题讨论】:

    标签: java android string


    【解决方案1】:

    原语没有任何字段或方法。有时编译器会将您的原语“自动装箱”到相应的类中,在这种情况下为Integer。也许这就是您在这种情况下所期望的。有时编译器不会这样做。在这种情况下,它不会自动自动装箱。

    你有几个选择:

    1. String.valueOf(nltxt)

    2. "" + nltxt(或者如果你有一些有用的东西要和号码一起写,请"nltxt equals " + nltxt

    3. 手动执行“自动装箱”:new Integer(nltxt).toString()

    4. 以某种自定义方式对其进行格式化:String.format("nltxt is %d which is bad%n", nltxt)

    【讨论】:

    • 我同意 3 有点复杂。但为什么不是 2?
    • aioobe:它的可读性不太好。如果有人快速浏览代码,他们可能会错过您只是试图将其转换为强代码。
    【解决方案2】:

    原始类型不是对象,因此没有任何方法。

    要将其转换为字符串,请使用String.valueOf(nlTxt)

    【讨论】:

      【解决方案3】:

      您也可以为此使用Integer.toString(nllen);

      【讨论】:

        猜你喜欢
        • 2012-04-15
        • 2013-11-11
        • 2018-11-03
        • 1970-01-01
        • 2014-05-19
        • 2013-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多