为什么一个 char + 另一个 char = 一个奇怪的数字

why does a char + another char = a weird number(为什么一个 char + 另一个 char = 一个奇怪的数字)
本文介绍了为什么一个 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.valueOfCharacter.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 is String, 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.

这执行基本的 intchar 转换.

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 = 一个奇怪的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)