简体   繁体   English

计算字符输入的次数-Do-While循环Java

[英]Counting number of times a character is inputted--Do-While Loops Java

I'm a bit confused as to why I need the do-while loop in this piece. 我对于为什么需要这段代码中的do-while循环有些困惑。 What I am trying to do is count the number of times a user inputs a character. 我想做的是计算用户输入字符的次数。 The count should stop when the user types a ".". 用户键入“。”时,计数应停止。 When I try to run the program without the do-while, the count of x is multiplied by 3. I've read online that the console input is line buffered. 当我尝试不带do-while的情况下运行程序时,x的计数将乘以3。我已经在线阅读控制台输入是行缓冲的。 The way I understand it, is a an entire line is created by one character and as such there are actually more characters? 以我的理解,整行是由一个字符创建的,因此实际上有更多字符吗? Is my understanding correct? 我的理解正确吗? And if possible, could I have an explanation of the do-while loop? 如果可能的话,我能解释一下do-while循环吗?

public class readCharLengths {
public static void main(String args[]) 
    throws java.io.IOException {
        char typed, ignore;
        int x=0;  
        for ( ; ; ) {      //infinite loop to keep reading in values

            typed = (char) System.in.read();      //get typed character

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

                    if (typed =='.') break;       //break loop when . is typed
            x++;                                  //increment x

        }

     System.out.println("The number of characters is: " + x);   //print x

}
}

It depends on the circumstances around how a user is giving input into the console. 这取决于用户如何向控制台提供输入的环境。 If they insert one character at a time, each on a separate line. 如果它们一次插入一个字符,则每个字符都放在单独的行上。 Or if they input a string of characters, basically like a sentence, and then you count the number of characters until a period is reached. 或者,如果他们输入了一个字符串(基本上像一个句子),然后您要计算直到达到句点为止的字符数。

If it is one character per line, I would suggest: 如果每行一个字符,我建议:

    int x = 0;
    Scanner in = new Scanner(System.in);
    while (true) {
        String input = in.nextChar();
        if (input.equals('.') {
            break;
        } else {
            x++;
        }
    }

If it is a string of characters, I would suggest: 如果是字符串,我建议:

    int x = 0;
    Scanner in = new Scanner(System.in);

    String input = in.nextLine();

    for (int i=0; i<input.length(); i++) {
        if (input.charAt(i).equals('.') {
            break;
        } else {
            x++;
        }
    }

Well, there are a couple of things about this. 好吧,关于这件事有两件事。

First, this might not do what you want because the do/while loop will consume every character after the first one without incrementing the counter until it hits the LF. 首先,这可能无法满足您的要求,因为do / while循环将消耗第一个字符之后的每个字符,而不会递增计数器直到命中LF。 So, your count will always be 1 with the do/while loop in place assuming you type at least one character and then hit Enter. 因此,假设您至少键入了一个字符然后按Enter,则在执行do / while循环的情况下,您的计数将始终为1。 However, if your intention is that the user is allowed to enter only one character at a time (followed by Enter), then see the second item. 但是,如果您打算让用户一次只能输入一个字符(其次是Enter),则请参阅第二项。

Second, console input defaults to buffered until you press Enter. 其次,控制台输入默认为缓冲,直到您按Enter键为止。 So, if you take the do/while loop out, enter a single character and press Enter, you'll actually get three characters on Windows--the character you typed, CR and LF. 因此,如果您执行do / while循环,输入一个字符并按Enter键,您实际上将在Windows上获得三个字符-您键入的字符CR和LF。 Assuming you're testing with single characters, that would explain the multiplication by 3. 假设您使用单个字符进行测试,这将说明乘以3。

To answer what a do...while loop is, I'm going to go into some very basic programming concepts. 为了回答do ... while循环是什么,我将介绍一些非常基本的编程概念。 I don't mean to be condescending if I come across that way: I just don't know your skill level with programming, so I'm assuming you are very new to it. 我并不是想屈服于这种方式:我只是不知道您的编程技能水平,所以我假设您对此非常陌生。

First, let me explain the concept of a loop condition. 首先,让我解释循环条件的概念。 A loop condition is code that, when it is evaluated while your program runs, will either come out to true or false . 循环条件是在程序运行时对其求值时将变为truefalse So, in the case of a regular while loop, the format is: 因此,在常规while循环中,格式为:

while (loop condition) {
    run some code, maybe multiple times
}

When your code reaches the while line of code it evaluates the condition and decides whether to run the code inside the loop's braces. 当代码到达while代码行时,它将评估条件并决定是否在循环括号内运行代码。

Let's say your condition is "x must be less than 5". 假设您的条件是“ x必须小于5”。 You might have a while loop like this: 您可能会有一个while循环,如下所示:

int x = 0;
while(x < 5) {
   System.out.println("A");
   x++;
}

This code will print A on 5 lines because x = 0 when it reaches the while statement the first time, and since 0 < 5 evaluates to true , the loop's code is going to execute. 该代码将在5行上打印A,因为当x = 0第一次到达while语句时为0 < 5 ,并且由于0 < 5计算结果为true ,因此将执行循环的代码。 When the end of the loop is reached, it jumps up to the loop condition and evaluates it again. 到达循环末尾时,它将跳至循环条件并再次评估。 This time, x = 1 because we added 1 to x. 这次, x = 1因为我们在x上加了1。 Since 1 < 5 , the loop happens again. 由于1 < 5 ,循环再次发生。 This happens a total of 5 times and then when it evaluates the loop condition, you have it try 5 < 5 , which is false . 总共发生5次,然后在评估循环条件时,尝试5 < 5 ,这是false It skips the loop code and continues the program at this point. 它跳过循环代码,并在此时继续执行程序。

A do...while loop is based on the same idea. do ... while循环基于相同的想法。 Instead of checking the loop condition at the start of the loop, it is checked at the end. 而不是在循环开始时检查循环条件,而是在结束时检查它。 So... 所以...

int x = 0;
do {
  System.out.println("A");
} while(x < 0);

This code will output A once. 此代码将输出一次A。 Even though the loop condition is not met (since x starts at 0), when you use a do...while, the loop code is always executed at least once. 即使不满足循环条件(因为x从0开始),当您使用do ... while时,循环代码始终至少执行一次。 At the end of the loop, the condition is checked and since 0 < 0 is false , the loop does not repeat. 在循环结束时,将检查条件,并且由于0 < 0false ,因此循环不会重复。


So, on to how System.in.read() works. 因此,有关System.in.read()工作方式。 You have it right that it buffers the input until a linebreak is reached. 您完全可以缓冲输入,直到达到换行符为止。 But do you actually know what that means? 但是您实际上知道这意味着什么吗?

Here's how it works. 运作方式如下。 You start typing stuff into the console. 您开始在控制台中输入内容。 Say you type aabbcc and then press enter. 假设您键入aabbcc ,然后按Enter。 Your program waits when it calls System.in.read() until user input is sent back to the program. 您的程序在调用System.in.read()之前会一直等待,直到将用户输入发送回该程序为止。 It does not continue running when the first a is typed though! 但是,当键入第a时,它不会继续运行! Your program only gets to continue running once you press enter (that is, a linebreak is sent). 按下Enter键(即,发送换行符)后,程序才能继续运行。

The idea of buffering input is that all the letters you typed are stored and available once your program starts running again. 缓冲输入的想法是,一旦您的程序再次开始运行,您输入的所有字母都将被存储并可用。 So when your program runs after you have entered aabbcc , all of those letters are available (and also the linebreak for the enter key you pressed). 因此,当您在输入aabbcc之后运行程序时,所有这些字母都可用(以及您按下的Enter键的换行符)。

With your code, that means that the first time you call System.in.read() , you get back the character a , but there is still abbcc and newline waiting. 对于您的代码,这意味着您第一次调用System.in.read() ,将获得字符a ,但是仍然有abbcc和换行符在等待。 It enters the loop and reads each character. 它进入循环并读取每个字符。 So it reads a , then b , then b , then c , then c , then newline. 因此,它将读取a ,然后b ,然后b ,然后c ,然后c ,然后换行。 At this point the loop condition is false and the loop ends. 此时,循环条件为false ,循环结束。

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

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