原来的问题是这样的.
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.
我想知道为什么.
您可以在此处验证a,b和c(或任何其他字符)的值.
编辑:要解释为什么最后一个输出正确的值而不是抛出错误,您首先将所有值加总,如前所述,然后将其转换为字符串,将""添加到字符的ASCII值之和.但是,println方法需要一个String,这就是它不会抛出任何错误的原因.
如果你愿意的话,第一个会起作用 Integer.parseInt('1' + '2' + '3' + "");