为什么线多次打印?

时间:2014-10-13 01:59:07

标签: java while-loop

我希望打印行"Enter character: ",然后获取输入字符并分配它,然后继续重做,直到-?为输入。但是,"Enter character: "在最初打印一次后第一次输入后会多次打印。输入'?''-'也不会退出循环。

以下是方法:

    private void runPrompt() {
    Deque<Character> first = new Deque<Character>();
    Deque<Character> second = new Deque<Character>();
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            System.in));
    char userChar = 0;
    int firstWord = 0;
    int secondWord = 0;
    boolean isMinus = false;
    while (!isMinus) {
        System.out.print("Enter character: ");
        try {
            userChar = (char) reader.read();
            System.out.println(userChar);
            first.enqueue(userChar);
            firstWord++;
            if (userChar == '-') {
                isMinus = true;
            }
        } catch (QueueException e) {
            System.out.println(e.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (isMinus) {
        while (userChar != '?') {
            System.out.print("Enter character: ");
            try {
                userChar = (char) reader.read();
                System.out.println(userChar);
                second.enqueue(userChar);
                secondWord++;
            } catch (QueueException e) {
                System.out.println(e.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    switch (checkLength(firstWord, secondWord, isMinus)) {
    case 0:
        System.out.print("\t>>Same length, ");
        if (checkContent(first, second)) {
            System.out.print("Same content, ");
            if (checkPalindrome(first, firstWord)) {
                System.out.println("Palindrome");
            }
        } else {
            System.out.println("Different content, no Palindrome");
        }
        break;

    case 1:
        System.out
                .println("\t>>Left longer, different content, no Palindrome");
        break;

    case 2:
        System.out
                .println("\t>>Right longer, different content, no Palindrome");
        break;

    case 3:
        System.out.println("\t>>No minus");

    default:
        break;
    }
}

以下是样本输出的方法:

    Enter character: r
    r
    Enter character: 

    Enter character: 

    Enter character: 

1 个答案:

答案 0 :(得分:1)

由于它逐个字符地读取,它实际上读取r,然后是回车(CR)字符,最后是换行(LF)字符。你可以打印价值&amp;亲眼看看:

System.out.println((int)userChar);

它显示了我提到的字符的UTF-16代码单元值。因此,根据输入,循环将再执行两次。然后它回来&amp;等待下一个输入 - 这就是为什么总共有四个Enter character:语句可见。您可以使用类似readLine().charAt(0)的内容来避免这种情况。可能有一些方法来刷新缓冲区中的挂起输入,但现在不记得它。