Dwa*_*ali 1 java string-concatenation type-conversion
我需要打印“ H3110 w0r1d 2.0 true ”作为输出。下面是编写并获得输出为“3182 w0r1d 2.0 true”的代码。
public class HelloWorld {
public static void main (String[] args){
char c1= 'H';
int num1 = 3110;
char c2='w';
byte b=0;
char c3='r';
int y=1;
char c4='d';
float f = 2.0f;
boolean bool= true;
String s = c1+num1 + " " + c2+b+c3+y+c4 + " " + f + " " + bool;
System.out.println(s);
}
}
Run Code Online (Sandbox Code Playgroud)
查询:如果我连接H和3110,则打印为3182。为什么这样?
该+除非至少有一个操作数的类型的运营商不使用字符串连接String。忽略其余的+运算符,您基本上是在寻找“如果我将char和加int在一起会发生什么” - 答案是“char被提升为int,并执行正常的整数加法”。的提升值为'H'72(因为这是 'H' 的 UTF-16 数值),因此结果为 3182。
在您的情况下,最简单的解决方法是将类型更改为c1toString而不是char:
String c1 = "H";
Run Code Online (Sandbox Code Playgroud)
然后将使用字符串连接而不是整数加法。
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |