【问题标题】:Why is it subtracting incorrectly from char?为什么它从 char 中错误地减去?
【发布时间】:2014-10-30 23:27:06
【问题描述】:

这是我的代码:

public class charTest
{
  public static void main(String[] args)
  {
    String bigNum = ("789");
    char s1 = bigNum.charAt(0);
    System.out.println(s1);
    System.out.println(s1-1);
  }
}

它在第一行打印 7,然后在下一行打印 54,为什么?我有一个非常长的数字作为字符串,我在其中单独引用单个数字。我刚刚做了减法测试,看看它是否工作正常。有什么见解吗?

【问题讨论】:

    标签: java math char int


    【解决方案1】:

    7(字符)的 unicode 点值为55。减去1 得到54

    第一个println 语句使用char 参数,而第二个语句使用int(从char 减去int 导致wideningint

    你可以得到6

    System.out.println(Character.getNumericValue(s1) - 1);
    

    【讨论】:

    • 不是 ASCII。 charAt 返回一个 Unicode/UTF-16 代码单元。
    【解决方案2】:

    s1 是一个字符,因此可以打印。 s1 - 1 被隐式转换为 int,因为打印为 int。即对 54 的值调用 toString 方法。

    【讨论】:

      猜你喜欢
      • 2021-02-01
      • 1970-01-01
      • 2019-03-18
      • 2022-06-11
      • 1970-01-01
      • 2021-10-15
      • 2020-08-12
      • 1970-01-01
      • 2021-01-29
      相关资源
      最近更新 更多