why does a char + another char = a weird number(为什么一个 char + 另一个 char = 一个奇怪的数字)
问题描述
代码片段如下:
public static void main (String[]arg)
{
char ca = 'a' ;
char cb = 'b' ;
System.out.println (ca + cb) ;
}
输出是:
195
为什么会这样?我认为 'a' + 'b' 将是 "ab" 、 "12" 或 3代码>.
Why is this the case? I would think that 'a' + 'b' would be either "ab" , "12" , or 3.
这是怎么回事?
推荐答案
+ 的两个 char 是算术加法,而不是字符串连接.你必须做类似 ""+ ca + cb,或者使用String.valueOf和Character.toString方法保证+ 是一个String,用于操作符进行字符串连接.
+ of two char is arithmetic addition, not string concatenation. You have to do something like "" + ca + cb, or use String.valueOf and Character.toString methods to ensure that at least one of the operands of + is a String for the operator to be string concatenation.
如果 + 运算符的任一操作数的类型为 String,则该操作为字符串连接.
If the type of either operand of a
+operator isString, then the operation is string concatenation.
否则,+ 运算符的每个操作数的类型必须是可转换为原始数值类型的类型,否则会出现编译时错误.
Otherwise, the type of each of the operands of the + operator must be a type that is convertible to a primitive numeric type, or a compile-time error occurs.
至于为什么你得到 195,那是因为在 ASCII 中,'a' = 97 和 'b' = 98,以及 97 + 98= 195.
As to why you're getting 195, it's because in ASCII, 'a' = 97 and 'b' = 98, and 97 + 98 = 195.
这执行基本的 int 和 char 转换.
This performs basic int and char casting.
char ch = 'a';
int i = (int) ch;
System.out.println(i); // prints "97"
ch = (char) 99;
System.out.println(ch); // prints "c"
这忽略了字符编码方案的问题(初学者不应该担心......但是!).
This ignores the issue of character encoding schemes (which a beginner should not worry about... yet!).
作为注释,Josh Bloch 指出,很遗憾 + 对字符串连接和整数加法都进行了重载(对于字符串连接重载 + 运算符可能是一个错误." -- Java Puzzlers,谜题 11:最后的笑声).通过使用不同的字符串连接标记可以轻松避免很多此类混淆.
As a note, Josh Bloch noted that it is rather unfortunate that + is overloaded for both string concatenation and integer addition ("It may have been a mistake to overload the + operator for string concatenation." -- Java Puzzlers, Puzzle 11: The Last Laugh). A lot of this kinds of confusion could've been easily avoided by having a different token for string concatenation.
- 是与空字符串连接进行字符串转换真的那么糟糕吗?
这篇关于为什么一个 char + 另一个 char = 一个奇怪的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么一个 char + 另一个 char = 一个奇怪的数字
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
