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

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

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

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

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)