0
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);
    } 
}

i couldn't get expected result.

xenteros
  • 15,586
  • 12
  • 56
  • 91
Subash Hamal
  • 1
  • 1
  • 2
  • 2
    Works fine for me. What is your expected result? Or are you confused about the double "Pass #" output per entered char? – Tom Dec 09 '16 at 12:44
  • 1
    What is the expected result? I would expect that the above loop stops upon entering S. – GhostCat Dec 09 '16 at 12:45
  • i wanted a infinite loop that stop after pressing S so that i don;t have to push enter after certain output – Subash Hamal Dec 09 '16 at 13:29
  • http://stackoverflow.com/questions/17555515/how-to-get-input-without-pressing-enter-every-time – Tom Dec 09 '16 at 13:33

1 Answers1

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?

Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353
  • Actually i wanted the loop to go on unless i enter 'S' such that i don't have to push enter after certain display i want it to be continue can we do that but this one is also helpful for me thank you. – Subash Hamal Dec 09 '16 at 13:25