简体   繁体   English

String charAt()方法在Java中如何工作?

[英]How does String charAt() method work in Java?

Why does the following code create compile error? 为什么以下代码会产生编译错误? Doesn't charAt() method return char datatype? charAt()方法不返回char数据类型吗?

public static void main (String[] args) throws java.lang.Exception
{
    String a = "abcd";
    char c = a.charAt(2)-'a';
}

error: incompatible types: possible lossy conversion from int to char

When you subtract two char s, they are promoted to int and the subtraction is performed on two int operands, and the result is an int . 当您减去两个char ,它们将被提升为int并且对两个int操作数执行减法,结果为int

You can cast to char to assign the result to a char : 您可以强制转换为char以将结果分配给char

char c = (char) (a.charAt(2)-'a');

Note that you might get unexpected results if the subtraction results in a negative value, since char can't contain negative values. 请注意,如果减法得出负值,则可能会得到意外的结果,因为char不能包含负值。

Besides, I'm not sure it makes any sense to subtract 'a' from a character and store the result in a char . 此外,我不确定从字符中减去“ a”并将结果存储在char是否有意义。 In your example, it will give you the character whose numeric value is 2, which has no relation to the character 'c'. 在您的示例中,它将为您提供数字值为2的字符,该字符与字符'c'无关。

Java Language Specification says: Java语言规范说:

  • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. 如果任何一个操作数是引用类型,则执行装箱转换(第5.1.8节)。 Then: 然后:
  • If either operand is of type double, the other is converted to double. 如果一个操作数的类型为double,则另一个将转换为double。
  • Otherwise, if either operand is of type float, the other is converted to float. 否则,如果其中一个操作数的类型为float,则另一个将转换为float。
  • Otherwise, if either operand is of type long, the other is converted to long. 否则,如果其中一个操作数的类型为long,则另一个将转换为long。

  • Otherwise, both operands are converted to type int. 否则,两个操作数都将转换为int类型。

So you need to explicitly cast it to char to get rid of the possible lossy error 因此,您需要将其显式转换为char,以消除可能的有损错误

char c = (char) (a.charAt(2)-'a');

Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable. 否则,将二进制运算的结果转换为左侧变量的类型,进行值集转换(第5.1.13节)为适当的标准值集(而不是扩展指数值集),然后将结果转换的结果存储到变量中。

charAt() method return char type But you are subtracting two char that will return int value in this case it will be 2 . charAt()方法返回char类型但是您要减去两个char,这将返回int值,在这种情况下为2。 So receive it into int it will work. 因此,将其接收到int它将起作用。

int c = a.charAt(2)-'a'; int c = a.charAt(2)-'a';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM