简体   繁体   中英

Not sure why my for loop isn't working the way i intended it to

So, before I start I just wanted to say that I'm very new to Java as a language and I've been reading a text book that was recommended to me. One of the examples provided within the text book on for loops had the following code, which is meant to generate an infinite for loop until the user presses the character 'S' on their keyboard.

Here is the code:

class ForTest {
    public static void main(String args[])
        throws java.io.IOException {
            int i;
            System.out.println("Press S to stop.");
            for (i = 0; (char) System.in.read() != 'S'; i++) 
                System.out.println("Pass #" + i);
                
        }
}

I copied the code exactly as it was written within the book but when I run the program, to my surprise, it doesn't start printing out numbers onto the console. Additionally, whenever I press any keys on the keyboard it generates three numbers within the sequence. Example shown below: 在此处输入图像描述

I have also included a screenshot of the code from the book below: 在此处输入图像描述

I was wondering whether anyone knows why this is the case. Any help would be greatly appreciated thanks.

The reason it's printing multiple times is because multiple characters are detected. In your case, it's printing twice because you entered a value ( Pass 1 ) and a new line ( Pass 2 )

The problem you have is not with System.in.read(), but because the console is usually using a buffered approach. Meaning that data is only transferred to the System.in.read() once you press enter.

So to get the example working, you would have to switch the console to an unbuffered mode, but there is no portable way to do this, because there are so much different types of consoles. Maybe have a look at what editor/console the book is using

This block of code looks like it was written by someone who was deliberately trying to make it obtuse and difficult to comprehend for a beginner.

The middle expression of a for statement is the criterion for taking the next step of the loop. It is evaluated before each step of the loop to determine whether the for loop is complete yet. In this case, it calls in.read() and checks if the input is S before each step of the loop.

in.read() waits for the next line of input it gets. When you enter a value and press Enter, that line gets read, so the loop takes a step. And a new line is also entered, so the loop takes a second step.

It will not print lines to the console unless you enter lines, because in.read() causes the program to block (wait) for the next input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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