所以我想将一个字符添加到一个字符串中,并且在某些情况下想要将该字符加倍然后将其添加到一个字符串中(即先添加到它本身).我试过了,如下所示.
So I wanted to add a character to a string, and in some cases wanted to double that characters then add it to a string (i.e. add to it itself first). I tried this as shown below.
char s = 'X';
String string = s + s;
这引发了一个错误,但我已经在字符串中添加了一个字符,所以我尝试了:
This threw up an error, but I'd already added a single character to a string so I tried:
String string = "" + s + s;
哪个有效.为什么在总和中包含一个字符串会导致它起作用?是否添加了一个字符串属性,由于字符串的存在,该属性只能由字符转换为字符串时使用?
Which worked. Why does the inclusion of a string in the summation cause it to work? Is adding a string property which can only be used by characters when they're converted to strings due to the presence of a string?
因为String + Char = String,类似于int + double = double.
It's because String + Char = String, similar to how an int + double = double.
尽管其他答案告诉你什么,Char + Char 是 int.
Char + Char is int despite what the other answers tell you.
字符串 s = 1;//由于类型不匹配导致的编译错误.
String s = 1; // compilation error due to mismatched types.
您的工作代码是 (String+Char)+Char.如果你这样做了: String+(Char+Char) 你会在你的字符串中得到一个数字.示例:
Your working code is (String+Char)+Char. If you had done this: String+(Char+Char) you would get a number in your string. Example:
System.out.println("" + ('x' + 'x')); // prints 240
System.out.println(("" + 'x') + 'x'); // prints xx - this is the same as leaving out the ( ).
这篇关于为什么我可以将字符添加到字符串但不能将字符添加到字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!