我正在读一本关于Java的教科书,我遇到了这段话。我有一些问题。
首先,这是书中提到的一些特殊转义字符。
’\n’ the newline character
’\t’ the tab character
’\0’ the zero character
’\’’ the single-quote character
’\"’ the double-quote character
’\\’ the backslash character
到目前为止没有问题。然后写道:
Newline and tab characters are often used in building strings that will be printed. For example, one might write
System.out.println ("Here’s a person:\t" + name + ’\t’ + age +
"\n\n");
但是它写道:
It would be better and safer to use "\t" instead of ’\t’ in the line above. If you wrote
System.out.println (age + ’\t’ + name);
the age and tab characters would be added as ints, which is probably not what the programmer intended. Writing
System.out.println (age + "\t" + name);
will cause both uses of the plus operator to be interpreted as concatenations.
为什么制表符周围的单引号使用不好?我不明白问题是什么或者为什么会发生?为什么 Java 解释器突然将 '\t' 解释为 int?
最佳答案
+
根据其参数之一是否为String
,工作方式有所不同或不。如果一个参数是 String
,然后另一个参数转换为 String
,和+
执行字符串连接。但如果两个参数都不是 String
,那么两个参数都必须是数字,并且结果是算术加法。 char
是数字类型( '\t'
的值为 9)。
当多个操作数与 +
串在一起时,就会出现困惑。 。考虑一下,其中 int1
和int2
是整数变量:
"String" + int1 + '\t' + int2
int1 + " String" + '\t' + int2
int1 + '\t' + "String" + int2
int1 + '\t' + int2 + "String"
+
同事从左到右。在第一个表达式中,程序计算 "String" + int1
首先,这意味着它将整数转换为 String
,结果是一个字符串(称之为 temp1
)。然后它计算temp1 + '\t'
,并且自 temp1
是 String
,它将转换 '\t'
到一个字符串(一个制表符的字符串)并连接。结果是另一个字符串(称之为 temp2
),然后是最后一个 +
将转换int2
到 String
并连接 temp2
有了它。
第二个表达式的工作方式类似,因为最左边的 +
有一个字符串操作数。这意味着所有 +
将是字符串连接运算符。
不过,第三个表达式有所不同。最左边+
正在添加两个整数(实际上是 int
和 char
),因此结果将是 int1 + 9
的结果,一个整数。那么,从下一个+
有一个String
操作数,该整数 ( int1 + 9
) 将转换为字符串并连接。这导致 String
,所以最后一个+
也是字符串连接,并且 int2
被转换为字符串。
在最后一种情况下,第一个和第二个 +
都是整数加法。所以这里的结果是 int1 + int2 + 9
被计算;然后结果被转换为字符串并与字符串文字连接。
我认为这就是文本所指的内容。尽管第一个示例可以工作,但很容易发生意外,因为如果您决定重做表达式并消除第一个字符串文字,则所有 +
的含义将被删除。运算符会突然变为算术加法。
请注意,这仅适用于 +
运算符(operator)。这是唯一具有这种特殊重载属性的运算符。
关于java - Java 中的特殊字符。您可以在此 printf 方法调用中使用单引号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502925/