如果我将long
变量声明为:
long n = 1E+12L;
编译器抛出语法错误。
并且当我声明为:
long n = 1E+12;
引发不兼容的类型错误。
另一方面,很高兴在浮点数和双打中接受两个字母:
double n = 1E+12D;
float n = 1E+12F;
为什么它不适用于long
文字?我是否必须每次都删除L字母并将其转换为long
?
不,这是不可能的。 Java语言规范e
中不允许在数字文字(即E
)中使用scientific notation或integer literals:
IntegerLiteral:
DecimalIntegerLiteral
HexIntegerLiteral
OctalIntegerLiteral
BinaryIntegerLiteral
DecimalIntegerLiteral:
DecimalNumeral [IntegerTypeSuffix]
...
IntegerTypeSuffix:
(one of)
l L
floating-point literals允许,但是不能有l
或L
后缀:
FloatingPointLiteral:
DecimalFloatingPointLiteral
HexadecimalFloatingPointLiteral
DecimalFloatingPointLiteral:
Digits . [Digits] [ExponentPart] [FloatTypeSuffix]
. Digits [ExponentPart] [FloatTypeSuffix]
Digits ExponentPart [FloatTypeSuffix]
Digits [ExponentPart] FloatTypeSuffix
ExponentPart:
ExponentIndicator SignedInteger
ExponentIndicator:
(one of)
e E
...
因此,您必须完整写出long
文字。但是,为方便起见,您可以使用下划线将数字分组,例如1_000_000_000_000L
,以使零数清晰可见。