简体   繁体   English

Java char变量

[英]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 . 编译器知道90char的有效值。 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. 如果将-1char ,则将得到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 streams InputStreamReader是从字节流到字符流的桥梁

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

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