首页 > 解决方案 > System.out.print("") 在控制台被 Scanner(System.in) 停止之前不打印,ei 光标只是在等待

问题描述

这是代码:

private boolean getPlayerAction() {
        while (player.getHandValue() < 21) {
            System.out.print("Do you want to Hit or Stand?: ");
            char c = getInput();
            switch (c) {
                case 'h' -> {
                    player.setCard(dealer.dealCard());
                    System.out.println(player.toString());
                }
                case 's' -> {
                    return true;
                }
                default -> System.out.println("Invalid entry, try again.");
            }
        }
        if (player.getHandValue() > 21) {
            System.out.println("Sorry. You bust.");
            return false;
        }
        return true;
    }

private char getInput() {
        String input = in.nextLine();
        if (!input.isEmpty()) return input.toLowerCase().charAt(0);
        return 'b';
    }

这是输出:

Dealer is showing 10 with QS 
You have 13 with 3H JC 

它应该有提示:“Do you want to Hit or Stand?:”空白行在哪里。如果我点击输入,输出如下所示:

Dealer is showing 10 with QS 
You have 13 with 3H JC 

Do you want to Hit or Stand?: Invalid entry, try again.

附加说明,我尝试使用 println() 而不是 print() 运行它,它可以正常工作,但是使用 print() 我得到了时髦的怪异。

标签: java

解决方案


您可能需要刷新输出才能看到它出现在您希望的位置。

尝试添加:

System.out.flush();

就在你之后System.out.print("Do you want to Hit or Stand?: ");


推荐阅读