Why can I add characters to strings but not characters to characters?(为什么我可以将字符添加到字符串但不能将字符添加到字符?)
问题描述
所以我想将一个字符添加到一个字符串中,并且在某些情况下想要将该字符加倍然后将其添加到一个字符串中(即先添加到它本身).我试过了,如下所示.
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 ( ).
这篇关于为什么我可以将字符添加到字符串但不能将字符添加到字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我可以将字符添加到字符串但不能将字符
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
