【发布时间】:2020-07-25 08:43:23
【问题描述】:
代码:
import java.io.*;
public class BufferedInputStreamDemo {
public static void main(String[] args) throws IOException {
String phrase = "Hello World #This_Is_Comment# #This is not comment#";
byte[] bytes = phrase.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
BufferedInputStream bin = new BufferedInputStream(in);
int character;
boolean com = false;
while ((character = bin.read()) != -1) {
switch(character) {
case '#' :
if (com) com = false;
else {
com = true;
bin.mark(1000);
}
break;
case ' ' :
if (com) {
com = false;
System.out.print('#');
bin.reset();
}
else {
System.out.print((char)character);
}
break;
default : if (!com) System.out.print((char)character);
}
}
in.close(); bin.close();
}
}
这段代码有什么作用?
此代码读取字符串,bufferStream 删除/隐藏 cmets。这里的 cmets 用 #this_is_comment# 表示,带有 ' ' (空格)的 cmets 不被视为注释 ex : #这不是评论#。
问题:
每当遇到''(空格)并且 com(布尔值,当 true 不读取流)为 true 时,它会将流恢复到标记的位置,我怀疑如果它恢复,# 不是再次遇到并且 com 将被设置为 false 因此考虑它的评论。
case '#' :
if (com) com = false;
else {
com = true;
bin.mark(1000);
}
但这不是输出正确的情况。
如果可能,请编辑问题以使其更易于理解。
【问题讨论】:
-
标记的位置是你调用
mark()时所处的位置。在这种情况下,您已经阅读了#,因此您的当前位置晚了一个字节。