简体   繁体   English

什么是Java中缓冲的行?

[英]What is a line buffered in Java?

I'm having a little problems about Java input. 我在Java输入方面有一些问题。 My code is a guessing letter game.(I read it from a book.) Here's my code. 我的代码是一个猜字母游戏。(我从书中读取了它。)这是我的代码。

public class Guess4 {
    public static void main(String args[])
    throws java.io.IOException{
        char ch, ignore, answer = 'K';

        do{
            System.out.println("I'm thinking of a letter between A and Z.");
            System.out.print("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're ");
                if(ch<answer) System.out.println("too low.");
                else System.out.println("too high.");
                System.out.println("Try again!\n");
            }
        }while(answer != ch);
    }

I do not understand why this block of codes is necessary. 我不明白为什么需要这段代码。

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

When this block is deleted. 删除该块时。 The output came out differently. 输出结果不同。

The book did said something about the line buffered but I still don't understand. 这本书确实说了有关缓冲线的内容,但我还是不明白。 Can anyone explain what a line buffered is? 谁能解释缓冲的行是什么?

Thank you. 谢谢。

The program is asking the user to enter a single letter. 该程序要求用户输入一个字母。 But System.in is buffered. 但是System.in已被缓冲。 The user can actually type several characters. 用户实际上可以键入几个字符。 Even a long sentence. 甚至很长的句子。 Until finally he presses the Enter, which is character '\\n'. 直到最后他按下Enter键,即字符'\\ n'。

The program reads a character into ch: 该程序将一个字符读入ch:

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

Then it goes further, and keeps reading until it finds a '\\n' character: 然后它走得更远,并继续阅读直到找到'\\ n'字符:

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

If you don't do this step, then any extra input the user entered will get carried over for the next iteration of the outer loop. 如果您不执行此步骤,那么用户输入的任何其他输入都将被带入外循环的下一次迭代。 You don't want anything carried over, you want just the first character entered, discard the rest, so that in the next iteration you start with a clean buffer. 您不希望遗留任何东西,只希望输入第一个字符,而丢弃其余字符,以便在下一次迭代中从一个干净的缓冲区开始。

Try the code with the loop with ignore commented out. 尝试使用带有注释掉的循环的代码。 If you enter a single letter, the outer loop will run twice, for the letter you entered and the '\\n' character that ended your input. 如果输入单个字母,则外循环将运行两次,即输入的字母和结束输入的'\\ n'字符。 If you enter multiple letters, let's say "hello", the loop will run 6 times, 5 times for the letters hello and one more time for the '\\n' character that ends input. 如果您输入多个字母,比如说“ hello”,则循环将运行6次,字母hello重复运行5次,结束输入的'\\ n'字符再重复运行一次。

-> The loop with ignore is necessary to clear the input buffer. ->使用ignore的循环对于清除输入缓冲区是必需的。

When you enter text via the console the input will typically be sent to the program only when you press "Enter" or "Return". 当您通过控制台输入文本时,通常仅在您按“ Enter”或“ Return”时,输入才会发送到程序。 The program will then get the full line (including the newline character \\n marking the end of the line) and not only the one character you are interested in. 然后,程序将获得整行(包括换行符\\n标记该行的结尾),而不仅仅是您感兴趣的一个字符。

The while loop deals with these extra characters and throws them away. while循环处理这些多余的字符并将其丢弃。

It's the nextline character, that comes from pressing the enter key. 这是下一行字符,它来自按Enter键。 If you're to type a letter (let's say A ) and press enter, the characters that you get from System.in will be A\\n (2 characters). 如果要键入一个字母(假设为A )并按Enter,则从System.in获得的字符将为A\\n (2个字符)。

The \\n is then removed from the input buffer so it doesn't mess up the logic of the program. 然后,将\\n从输入缓冲区中删除,因此不会弄乱程序的逻辑。

You're probably reading an old book, since newer ones tend to use the Scanner class which is simpler than reading from System.in . 您可能正在读一本旧书,因为较新的书倾向于使用Scanner类,该类比从System.in阅读要简单。 You might want to consider some other reading material, since reading an outdated book can result in some funny ideas. 您可能需要考虑其他阅读材料,因为阅读过时的书可能会产生一些有趣的想法。

Judging by the code I suppose the input of the following code would be something like : 通过代码判断,我想以下代码的输入将类似于:

A
J
K

So at the third attempt it would print Success . 因此,在第三次尝试时,它将打印成功 But if you look at the input stream (as the system represents it) it looks like : A\\nJ\\nK\\n . 但是,如果您查看输入流(如系统所示),则看起来像: A\\nJ\\nK\\n Now your code goes through the input stream to find a valid input and reads all the characters after the first one till the \\n character as junk ie ignores it. 现在,您的代码将遍历输入流以查找有效输入,并读取第一个字符之后的所有字符,直到\\n字符成为垃圾字符,即忽略它。

So if the input stream is like AK\\nKA\\n it will print success at the second attempt and not at the first as it ignores all characters after 1 character of input ie A for the first and K for the second line. 因此,如果输入流像AK\\nKA\\n ,它将在第二次尝试而不是第一次尝试时成功打印,因为它将忽略输入1个字符之后的所有字符,即第一行为A ,第二行为K

If you remove the block you mentioned, then your code reads all the characters in the input stream including \\n which would obviously not match to K . 如果删除您提到的块,那么您的代码将读取输入流中的所有字符,包括\\n ,这些字符显然与K不匹配。

A buffered input stream processes the input removing any extra junk characters for you to just read the input. 缓冲的输入流处理输入,删除所有多余的垃圾字符,让您仅读取输入。 eg: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 例如: BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

This passes the System.in stream to an Reader object and BufferedReader does all the magic. 这会将System.in流传System.in Reader对象,并且BufferedReader发挥了所有作用。 There is much more to these classes once you get into a little more depth. 一旦深入一点,这些课程的内容就会更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM