如何使用char停止无限循环(从键盘method-System.in.read()输入.System.in?

时间:2016-12-09 12:38:33

标签: java loops input

class Copied{
    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);
    } 
}

我无法得到预期的结果。

1 个答案:

答案 0 :(得分:0)

What the above code does tricky is

(char) System.in.read() != 'S'

the .read() would

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255

So, your input are treated as :

Input : a
Output  : Pass #0 // for a
Pass #1 //for Enter


Input : all
Output : Pass #2 // a
Pass #3 //l
Pass #4 //l
Pass #5 // Enter

and similarly for any string unless it includes a character S

Input : stingWithSHere
Output : Pass #6 //s
Pass #7 //t
Pass #8 //i
Pass #9 //n
Pass #10 //g
Pass #11 //W
Pass #12 //i
Pass #13 //t
Pass #14 //h

and then it terminates. Hope that makes things look clear.


To strictly restrict the input from the user you can instead use -

new Scanner(System.in).next(".").charAt(0) != 'S'

With the updated question, the link shared by @Tom answers it for now -

How to get input without pressing enter every time?