我在数据结构分配(霍夫曼代码)中使用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); //<--WorksI 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.
更多推荐
发布评论