【问题标题】:Java String ManupulationJava 字符串操作
【发布时间】:2015-03-08 16:31:13
【问题描述】:

为什么下面的语句会出错

       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);
    }
}

【问题讨论】:

标签: java


【解决方案1】:
char x = 'A';
int temp = x;
temp = temp+1;
x = (char) temp;
System.out.println(x + " " + temp);

试试这个代码,因为char 到int 的转换是隐式的,而int 到char 是显式的转换。

【讨论】:

    【解决方案2】:

    您正在尝试进行向下转换(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);
    

    【讨论】:

    • "不能从 char 转换为 int" - 是的,你可以。
    • @xehpuk 是一个错字,实际上是想说(int to char),谢谢
    猜你喜欢
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多