【问题标题】:Why can I not concatenate Integer.toBinaryString() to another string in Java?为什么我不能将 Integer.toBinaryString() 连接到 Java 中的另一个字符串?
【发布时间】:2016-04-09 02:53:05
【问题描述】:

我正在尝试将整数输入转换为二进制字符串并将它们连接在一起形成一个长字符串。示例:

input: 4 5
output: 0100 0101

在查看 API 并看到 toBinaryString 返回一个字符串后,我确信我的解决方案应该可以工作,但它没有。

我的解决方案:

String str = "5 in binary: ";
str.concat(Integer.toBinaryString(5));

String str = "5 in binary: ";
str + Integer.toBinaryString(5);

每一个都只会打印出原始字符串“5 in binary:”而不是“5 in binary: 0101”。

toBinaryString() 返回一个字符串值,所以这应该是可能的吗?

【问题讨论】:

  • 字符串是不可变的,所以 str.concat() 不会修改 str,它会创建一个新的 String 实例,该实例被丢弃,因为它没有分配给任何东西。

标签: java string-concatenation bin


【解决方案1】:

因为 String 是不可变的对象。 所以str + Integer.toBinaryString(5);不会改变str的内容。它只是返回另一个 String 对象。您需要将该新对象分配给 str 类似的东西:

str = str + Integer.toBinaryString(5);

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 2012-08-07
    相关资源
    最近更新 更多