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);
}
}
我无法得到预期的结果。
答案 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 range0
to255
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 -