【问题标题】:Why doesn't Character.toString give the error The method toString() in the type Object is not applicable for the arguments (int)为什么 Character.toString 不给出错误 Object 类型中的方法 toString() 不适用于参数 (int)
【发布时间】:2022-06-14 22:34:13
【问题描述】:

我正在使用 Java 中的字符并将整数转换为字符串。我从另一个项目中复制了一些代码,但没有收到错误,并将其粘贴到我当前的项目中。当我运行代码并且我一直得到相同的结果时,对象类型中的 toString() 方法不适用于参数(int),错误。为什么我只在一个项目中收到此错误,我该如何解决?

这是我的代码:

public class main {
   public static void main(String[] args) {
       int num = 115;
       String value = Character.toString(num); //<-- Error here
       System.out.println(value);
   }
}

【问题讨论】:

  • Character.toString() 接受 char 作为参数,但您将 int 传递给它。 javatpoint.com/post/java-character-tostring-method
  • 在更高版本中添加了 int 重载。
  • 我试过用 char 来
  • @RobertHarvey 这可以与 115 一起使用(通过编写 "" + (char) 115) - 但是如果 OP 想要使用 128512 - ????? 的代码点怎么办?使用Character.toString(int),即使这样也是允许的。

标签: java string character


【解决方案1】:

在 Java 11 中引入了一个 Character.toString(int),它接受一个代码点。换句话说,您可能在一个项目中使用 Java 11 或更高版本,而不是在另一个项目中,或者您正在针对 -release 8 或低于 11 的其他版本进行编译。

顺便说一句,你说你是“将整数转换为字符串”。这不是Character.toString(int) 所做的(它将整数Unicode 代码点转换为表示该代码点的一或两个字符串)。如果要将整数转换为字符串,请使用Integer.toString(int)String.valueOf(int)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 2018-01-09
    • 2017-09-06
    相关资源
    最近更新 更多