gpt4 book ai didi

java - 丢弃输入缓冲区中的字符?

转载 作者:行者123 更新时间:2023-11-30 03:17:08 26 4
gpt4 key购买 nike

我正在阅读一本 Java 简介书,我正在阅读涉及 do while 循环的部分。这是代码:

public class GuessingGameV4 {

public static void main(String[] args) throws java.io.IOException {

char ch, ignore, answer;

answer = 'K';

do {
System.out.println("I am thinking of a letter between A and Z");
System.out.println("Can you guess it?");

ch = (char) System.in.read();

do {
ignore = (char) System.in.read();
} while (ignore != '\n');

if (ch == answer) System.out.println("Right!!! ");
else {
System.out.print("Sorry you are ");
if (ch < answer) System.out.print("too low.\n");
else System.out.print("too high.\n");

System.out.println("Try again\n");
}
} while (answer != ch);
}
}

涉及忽略的内部 do while 循环是丢弃输入缓冲区中的字符的代码部分。

我只是想更多地澄清它实际上在做什么,因为书籍的解释并不适合我。

最佳答案

我想这就是给你带来麻烦的部分:

System.out.println("I am thinking of a letter between A and Z");
System.out.println("Can you guess it?");

ch = (char) System.in.read();

do {
ignore = (char) System.in.read();
} while (ignore != '\n');

程序要求用户输入一个字母。但System.in 已被缓冲。用户实际上可以键入多个字符。甚至是很长的一句话。直到最后他按下 Enter 键,这是字符 '\n'

程序将一个字符读入ch:

ch = (char) System.in.read();

然后继续读取,直到找到 '\n' 字符:

do {
ignore = (char) System.in.read();
} while (ignore != '\n');

如果您不执行此步骤,那么用户输入的任何额外输入都将被保留到外循环的下一次迭代中。你不想带走任何东西你只想输入第一个字符,丢弃其余的,这样在下一次迭代中您就可以从干净的缓冲区开始。

尝试使用注释掉 ignore 的循环代码。如果您输入一个字母,外循环将运行两次,您输入的字母和结束输入的 '\n' 字符。如果输入多个字母,让我们说“你好”,循环将运行 6 次,对于字母 h-e-l-l-o 重复 5 次,对于结束输入的 '\n' 字符再重复一次。

-> 需要使用 ignore 循环来清除输入缓冲区。

关于java - 丢弃输入缓冲区中的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32287580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com