有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么字符连接返回“int”和?

问题说明了一切,以下是代码:

public class Chars
{

    public static void main(String[] args){
        Chars c = new Chars();
        String res = c.test("abcd");
        System.out.println(res);
    }

    public String test(String str){
        String res = "";
        res += str.charAt(0) + str.charAt(2); 
        return res;
    }
}

返回“196”,它是ac的ASCII值之和! 为什么会这样,我希望得到“ac”。 如果我修改test()方法中的第二行,如下所示:

res = res + str.charAt(0)+str.charAt(2);

结果确实是“ac”。 请有人帮我解答这个疑问。我就是找不到答案


共 (5) 个答案

  1. # 1 楼答案

    不同之处在于串联的构造方式

    第一:res += str.charAt(0) + str.charAt(2);

    这里,首先将两个char值相加。发生二进制数字升级(JLS, Section 5.6.2

    Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    • If either operand is of type double, the other is converted to double.

    • Otherwise, if either operand is of type float, the other is converted to float.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to type int.

    这意味着这些值被提升为int,从而创建196。然后将其添加到str,并附加"196"

    第二:res = res + str.charAt(0) + str.charAt(2);

    这里,首先执行res + str.charAt(0),并且String加上char附加char(通过String Conversion, JLS 15.18.1),产生新的String

    If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

    然后,类似地附加第二个char

    如果你说

    res = res + (str.charAt(0) + str.charAt(2));
    

    然后结果将与+=相同(附加196

  2. # 2 楼答案

    这是因为charAt()返回的是字符值,而不是字符串。因此这里的+运算符并不代表串联,而是两个数字的简单相加

    如果+的两个操作数都是一个数字,则此操作有效。如果其中一个是sString+不再形成加法,但两个操作数都被强制转换为String,并执行串联。因此,如果在混合中包含res,则

    res + str.charAt(0)
    

    将是一个String并且使用相同的逻辑,整个事情

    res += str.charAt(0) + str.charAt(2);
    

    也将被评估为String

  3. # 3 楼答案

    JLS §15.18.1. String Concatenation Operator +解释了原因:

    If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

    在您的情况下,您正在执行:char + char。操作数的Non类型为String,因此执行经典的数字加法

  4. # 4 楼答案

    通常,如果要从字符串中提取字符并获取长度为1的String,而不是char,请使用以下方法代替:

    str.charAt(i)
    

    您可以这样做:

    str.substring(i, i+1)
    

    或者这个:

    Character.toString(str.charAt(i))
    

    或:

    ("" + str.charAt(i))
    
  5. # 5 楼答案

    字符不是字符串。如果“a”和“c”是字符串,则期望得到“ac”。字符是表示字符的无符号整数,如果添加任意两个字符,结果将转换为int。如果要将其视为字符或将其分配给声明为char的变量,则必须使用(char)进行强制转换