添加"空间" Java中char的值

时间:2018-01-04 07:26:44

标签: java string char

按空格我的意思如下:

myString = ""; //This string is empty. It is not what I am talking about.
myString = " "; //This string has one space. It is what I am talking about.

现在,我尝试通过执行以下操作将空格设置为char:

char myChar = " ";

我收到以下错误:

incompatible types: String cannot be converted to char. 

基于此我猜猜引号中的内容总是被认为是Java中的字符串(如果我错了,请纠正我)。现在我正在做以下事情,它有效:

String emptyStr = " ";
char empty = emptyStr.charAt(0); //Tested it and the char does take a space value.

我的问题如下。 是否有更有效或已预先确定的方法?

1 个答案:

答案 0 :(得分:3)

根据我的理解,您正在尝试将空间值分配给char类型。但是您给出的值是一个字符串并尝试分配给char类型。如果您想要分配空格字符,请使用& #39; &#39 ;.

char mychar=' ';//this will work because assigning a char type in to char type

{{1}}