为什么我可以将字符添加到字符串但不能将字符添加到字符?

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 ( ).

这篇关于为什么我可以将字符添加到字符串但不能将字符添加到字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

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 中的默认语言环境设置以使其保持一致?)