[英]Java char variable
The following code within a program allows 90
to be assigned to the variable 'ch'. 程序中的以下代码允许将90
分配给变量“ ch”。 'Z' is then printed to the console. 然后将“ Z”打印到控制台。
char ch;
ch = 90;
System.out.println(ch);
However, the following code, that lies within a program, does not compile. 但是,位于程序内的以下代码无法编译。 If the following code requires the input to the ch
variable to be a character type, ie (char) System.in.read();
如果以下代码要求ch
变量的输入为字符类型,即(char) System.in.read();
, then why does the same not apply when 90
is assigned to ch
above? ,那么当上面的ch
分配了90
时,为什么同样不适用? Why doesn't it have to be ch = (char) 90
? 为什么不必一定是ch = (char) 90
?
char ch;
ch = System.in.read();
The compiler knows that 90
is a valid value for char
. 编译器知道90
是char
的有效值。 However, System.in.read()
can return any int
, which may be out of the valid range for char
s. 但是, System.in.read()
可以返回任何int
,这可能超出char
的有效范围。
If you change 90 to 90000, the code won't compile: 如果将90更改为90000,代码将无法编译:
char ch;
ch = 90000;
Whenever you are dealing with system io you need to ensure that you can handle all valid byte input values. 每当处理系统io时,都需要确保可以处理所有有效的字节输入值。 However, you then need a mechanism to indicate that the stream has been exhausted. 但是,您随后需要一种机制来指示流已耗尽。 The javadoc for InputStream.read()
( System.in
is a global InputStream
) says (emphasis added), InputStream.read()
的javadoc( System.in
是全局InputStream
)说(强调),
Reads the next byte of data from the input stream. 从输入流中读取下一个数据字节。 The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. 以0到255的范围内的int形式返回值字节。 如果由于已到达流的末尾而没有字节可用,则返回值-1。
If you were to cast -1
to char
you would get 65535 because char
is unsigned. 如果将-1
为char
,则将得到65535,因为char
是未签名的。 With byte
, it's even worse in that -1
is a valid value. 对于byte
,更糟糕的是-1
是有效值。 Regardless, you aren't reading char
values; 无论如何,您不是在读取char
值。 you are reading byte
(s) encoded as int
in the range 0-255 plus -1 to indicate end of stream. 您正在读取编码为int
byte
,范围为0-255加-1,以指示流的末尾。 If you want char
(s) I suggest you look at an InputStreamReader
which is described in the javadoc as 如果您想要char
建议您查看一个InputStreamReader
,它在javadoc中描述为
An
InputStreamReader
is a bridge from byte streams to character streamsInputStreamReader
是从字节流到字符流的桥梁
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.