[英]pushback stream example in java textbook help. What is going on?
I am reading this example in my java book: 我正在我的Java书籍中阅读此示例:
// Demonstrate unread().
import java.io.*;
class PushbackInputStreamDemo {
public static void main(String args[]) {
String s = "if (a == 4) a = 0;\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
int c;
try ( PushbackInputStream f = new PushbackInputStream(in) )
{
while ((c = f.read()) != -1) {
switch(c) {
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else {
System.out.print("<-");
f.unread(c);
}
break;
default:
System.out.print((char) c);
break;
}
}
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
Here is the output for this example. 这是此示例的输出。 Notice that == was replaced by ".eq." 请注意,==被“ .eq”替换。 and = was replaced by "<-". 和=替换为“ <-”。
if (a .eq. 4) a <- 0; 如果(a.eq. 4)a <-0;
When it reaches the single =
sign, it reads it, prints out the <-
and then unreads the =
and puts it back on the pushbackInputStream
right? 当到达单个=
符号时,它将读取它,打印出<-
,然后取消读取=
并将其放回pushbackInputStream
上,对吗? So when it calls c = f.read()
, it receives the =
again right? 因此,当它调用c = f.read()
,它会再次收到=
,对吗? so why aren't we in an infinite loop of <-
symbols? 那么为什么我们不陷入<-
符号的无限循环呢?
The while loop contains two possible branches: one when an =
character is encountered, and one for everything else. while循环包含两个可能的分支:一个在遇到=
字符时,另一个在其他所有分支上。 For the everything-else scenario the character is simply dumped out to the console, so no infinite loop is created. 对于其他所有情况,角色只是转储到控制台中,因此不会创建无限循环。
For the branch where we encounter an =
character, it will then read the next character (after that =
character) from the stream. 对于遇到=
字符的分支,它将从流中读取下一个字符(在=
字符之后)。 If the next character is a second =
character then .eq.
如果下一个字符是第二个=
字符,则.eq.
is dumped out to the console, and nothing is pushed back onto the PushbackInputStream
so the ==
sequence has been fully consumed and when we go around the while
loop again it finds whatever comes after the ==
. 被转储到控制台,并且没有任何内容被推回到PushbackInputStream
上,因此==
序列已被完全消耗,当我们再次绕过while
循环时,它将查找==
之后的内容。 So this scenario causes no infinite loop. 因此,这种情况不会导致无限循环。
If the next character after the first =
is not a second =
character then <-
is dumped out to the console, and then that second character is pushed back onto the stream. 如果第一个=
之后的下一个字符不是第二个=
字符,则将<-
转储到控制台,然后将该第二个字符推回流中。 Execution of the while
loop then re-reads this character and (seeing as we already know it is not an =
character) it will be dumped out to the console immediately after the <-
. 然后执行while
循环重新读取该字符,并且(如我们已经知道它不是=
字符),它将在<-
之后立即转储到控制台。 So this scenario does not cause an infinite loop. 因此,这种情况不会导致无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.