为什么StringReader.Read()没有返回一个字节?(Why doesn't StringReader.Read() return a byte?)

编程入门 行业动态 更新时间:2024-10-24 20:13:18
为什么StringReader.Read()没有返回一个字节?(Why doesn't StringReader.Read() return a byte?)

我在数据结构分配(霍夫曼代码)中使用StringReader,并且正在测试是否已到达字符串的结尾。 我发现StringReader.read()返回的int值不是-1,而是65535,所以将结果转换为一个字节解决了我遇到的无限循环问题。

这是JDK中的错误,还是通常的做法是将从Reader.read()调用返回的值转换为字节? 或者我错过了什么?

我的代码的要点是这样的:

StringReader sr = new StringReader("This is a test string"); char c; do { c = sr.read(); //} while (c != -1); //<--Broken } while ((byte)c != -1); //<--Works

I was using StringReader in a Data Structures assignment (Huffman codes), and was testing if the end of the string had been reached. I found that the int value that StringReader.read() returns is not -1, but 65535, so casting the result to a byte solved my infinite loop problem I was having.

Is this a bug in JDK, or is it common practice to cast values returned from Reader.read() calls to bytes? Or am I missing something?

The gist of my code was something like this:

StringReader sr = new StringReader("This is a test string"); char c; do { c = sr.read(); //} while (c != -1); //<--Broken } while ((byte)c != -1); //<--Works

最满意答案

实际上甚至没有编译。 我明白了:

类型不匹配:无法从int转换为char

由于sr.read()调用返回一个int我建议你这样存储它。

这编译(并按预期工作):

StringReader sr = new StringReader("This is a test string"); int i; // <-- changed from char do { i = sr.read(); // ... and if you need a char... char c = (char) i; } while (i != -1); // <-- works :-)

为什么StringReader.Read()没有返回一个字节?

字符串由16位unicode字符组成。 这些不适合8位字节。 有人可能认为一个char就足够了,但是没有空间提供EOF到达的指示。

In fact that doesn't even compile. I get:

Type mismatch: cannot convert from int to char

Since the sr.read() call returns an int I suggest you store it as such.

This compiles (and works as expected):

StringReader sr = new StringReader("This is a test string"); int i; // <-- changed from char do { i = sr.read(); // ... and if you need a char... char c = (char) i; } while (i != -1); // <-- works :-)

Why doesn't StringReader.Read() return a byte?

Strings are composed of 16-bit unicode characters. These won't fit in an 8-bit byte. One could argue that a char would have been enough, but then there is no room for providing an indication that the EOF is reached.

更多推荐

本文发布于:2023-04-29 08:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字节   Read   StringReader   return   byte

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!