在Java中,为什么输出int a =('a'+'b'+'c'); 是不同的形式System.out.println('a'+'b'+'c'+"")

Ret*_*ang 7 java

原来的问题是这样的.

public class test {
    public static void main(String[] args){
        int i = '1' + '2' + '3' + "";
        System.out.println(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from String to int
Run Code Online (Sandbox Code Playgroud)

然后我改变了这样的代码:

public class test {
    public static void main(String[] args){
        int i = '1' + '2' + '3';
        System.out.println(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是150.

但是当我写这样的代码时:

public class test {
    public static void main(String[] args){
        System.out.println('a'+'b'+'c'+"");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出变为294.

我想知道为什么.

Jea*_*ard 7

  • 第一个不编译,因为你在结尾连接一个String,导致值为一个不能直接转换为int的String.
  • 第二个的输出是150,因为字符1,2,3的ASCII值是49,50,51,在进行加法时返回150.
  • 最后一个的输出是294,因为你在ASCII表中添加了char值(97 + 98 + 99)

您可以在此处验证a,b和c(或任何其他字符)的值.

编辑:要解释为什么最后一个输出正确的值而不是抛出错误,您首先将所有值加总,如前所述,然后将其转换为字符串,将""添加到字符的ASCII值之和.但是,println方法需要一个String,这就是它不会抛出任何错误的原因.

如果你愿意的话,第一个会起作用 Integer.parseInt('1' + '2' + '3' + "");