简体   繁体   中英

Logic Error in Java For-loop

I am trying to make the loop continue to execute here until the user types the letter S at the keyboard. It seems to be giving three outputs instead of one for each iteration. What am I doing wrong here;

// Loop until an S is typed

public class ForTest {

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

        int i;

        System.out.println("Type S to stop.");

        for(i = 0; (char) System.in.read() != 'S'; i++) 
//          System.out.println("print");
            System.out.println("Pass # " + i);
//          System.out.println("print");


    }

}

Output coming up is if I press 'a':

Type S to stop.
a
Pass # 0
Pass # 1
Pass # 2

The InputStream.read method block until the end of input which is on a Windows OS the control characters CR LF (\\r\\n).

This explains why you get 3 characters as a result.

See for yourself :

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

    int i;

    System.out.println("Type S to stop.");

    char c = (char) 0;
    for (i = 0; c != 'S'; i++) {
        c = (char) System.in.read();
        System.out.println("Pass # " + i);
        System.out.println("char intValue : " + (int) c);
    }
}

Suggested read : Java: How to get input from System.console()

System.in will use BufferedInputSteam to read the input from console bit by bit (including the line break, etc). In Mac system, I get 2 bits whenever i gave a single digit input.

Use Scanner and read all the bytes and convert as String.

I suggest you to avoid reading input in that way, use Scanner instead. You can reach your goal with this code:

    int i = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Type S to stop.");
    while( !scan.next().equals("S")) {
        i++;
        System.out.println("Pass # "+i);
    }

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