Java字符串处理

收割者1

为什么下面的语句给出错误

       char rep=(str.charAt(len-1))-1;
       str.replace(str.charAt(len-1),rep);
       error: possible loss of precision

以下代码正常工作时

class test
{
    public static void main(String arg[])
    {
        char x='A';
        x=x+1;
        System.out.println(x);
    }
}
梦想家

您正在尝试进行downcasting(int --> char),这不是隐式的。您必须显式地进行强制转换

下面的代码将无法正确编译。

        char x='A';
        x=x+1;// can not convert from int to char implicitly.

更改为

        char x = 'A';
        x+=1;// it will automatically cast to char(implicit)

类似的更改您下面的代码行,您必须将其强制转换为char。

   char rep=(char)((str.charAt(len-1))-1);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章