循环,奇怪的结果

时间:2015-06-30 17:41:50

标签: java

我正在学习Java“Java:A Beginner's Guide”一书。 这本书展示了for循环的这个例子:

// Loop until an S is typed
class ForTest {
    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);
    }
}

输出是:

Press S to stop.
s
Pass #0
Pass #1
Pass #2
d
Pass #3
Pass #4
Pass #5
S

我不明白为什么每次按下不同的键盘键时,它会写三次Pass#。 我认为应该只写一次Pass#。 谢谢。

1 个答案:

答案 0 :(得分:6)

您按了s然后返回。 “return”生成了另外两个字符 - \r\n(我假设你在Windows上)。然后由System.in.read()返回。

这是一个更清晰的例子:

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

        int i;

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

输出:

Press S to stop.
a
Pass #0; c=97
Pass #1; c=13
Pass #2; c=10
b
Pass #3; c=98
Pass #4; c=13
Pass #5; c=10
S

\r是Unicode字符13,\n是10。

相关问题