可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
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
回答1:
The InputStream.read method block until the end of input which is on a Windows OS the control characters CR LF (rn).
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);
}
}
回答2:
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.
回答3:
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);
}