【问题标题】:Java - How to print() output to previous line after inputJava - 如何在输入后打印()输出到上一行
【发布时间】:2017-07-12 22:56:39
【问题描述】:

我是 Java 的新手,我仍在努力掌握它,所以如果这是一个愚蠢的问题,我深表歉意,但我想知道如何在与输入相同的行上打印输出.例如,我正在编写一个简单的游戏,用户尝试猜测一个 4 位数字(很像 Mastermind)。我已经弄清楚了所有机制,但是我很难在控制台上显示它。一开始它可能看起来像:(a)

Turn    Guess   Bulls   Cows
----------------------------
1

然后,用户将输入他们的猜测:(b)

Turn    Guess   Bulls   Cows
----------------------------
1       1234

一旦用户按下回车键,程序就会检查他们的猜测是否与密码相符,并输出“公牛”(他们猜测中的数字与密码完全匹配)和“奶牛”(他们猜测中的数字)的数量。猜测是数字的一部分但位置错误),然后开始一个新行并再次等待用户输入。因此,如果密码是 4321... (c)

Turn    Guess   Bulls   Cows
----------------------------
1       1234    0       4
2

问题是,我一生都无法弄清楚如何让输出显示在与输入相同的行上。这是我到目前为止所拥有的一个 sn-p(由于完整的代码更丑陋,因此被精简了):

number = "4321";
String guess;
int attempts = 1;
do
{
    System.out.print(attempts + "\t\t");
    guess = keyboard.next();
    attempts++;
    int bulls = checkBulls(guess, number);
    int cows = checkCows(guess, number);
    System.out.print("\t\t" + bulls + "\t\t" + cows + "\n");
}
while (!guess.equals(number));

这让我到了 (b),但是当我按下回车键时,会发生这种情况:

Turn    Guess   Bulls   Cows
----------------------------
1       1234                 // so far so good
    0       4                // ack! These should've been on the previous line!
2

我知道这对游戏来说并不是真正重要的,可能只是我让事情变得比必要的更复杂,但这让我疯了。我想发生的事情是,当您在输入猜测后按 Enter 键时,程序会开始一个新行,然后 然后 打印公牛和奶牛。有没有办法解决这个问题?

【问题讨论】:

  • 这不是一个愚蠢的问题。
  • 尝试在cli中构建一个ui
  • 我建议您使用类似stackoverflow.com/questions/18037576/… 的内容,只要您按下空格,就意味着输入已完成。我怀疑它是否适合进入。
  • 我认为在 Java 中没有内置函数可以做到这一点。有一个名为 JCurses 的 Java 诅咒库,您可以使用它。
  • 试着把它做成一个 GUI 应用程序

标签: java


【解决方案1】:

您应该查看Ansi Escape Codes

类似:

public void update() {
    final String guessString = keyboard.next();

    System.out.println("\033[1A\033[" + guessString.length() + 'C'
        + "\t{next col}");
}

将导致:

1234   {next col}

(其中 1234,后跟 {RETURN} 是用户输入的;在适当的支持控制台中。

"\033[1A" 将光标向上移动 1 行;并且"\033[xC" 将光标x 向右移动(上面我们计算x 作为他们猜测的长度)。

使用这种方法的另一个选择是清除控制台 ("\033[2J"),这样您就可以完全重新绘制表格(这可能更容易维护)。

【讨论】:

    【解决方案2】:

    您的问题是清除控制台或清除取决于您正在使用的控制台的行,并且非常依赖!

    Java Clear ConsoleJava clear Line

    无论如何,这个例子清除了这些行,它可以在 Unix bash shell 上运行。 (不在 Eclipse 控制台中) 它使用"\b" 清除字符(反斜杠)

     public static void main(String[] args) throws Exception {
            int i=0;
    
            while (true)
            {            
    
                String hello="Good morning"+i;
                System.out.print(hello+i);
                int j=0;
                while(j<=hello.length()){
                     System.out.print("\b");
                    j++;
                }
                i++;
                Thread.sleep(1000);
                if(i==100)
                    break;
            }
        }
    

    您的问题是您还需要清除新行,因为您读取了输入,并且没有新行就没有简单的方法来读取输入。 见How to read a single char from the console in Java (as the user types it)?

    【讨论】:

      【解决方案3】:

      我知道这不是你的实现,但它可能就足够了。您可以做的是在每次输入后打印游戏的进度。然后您可以在每次尝试后看到游戏的进度,并且每次都会更新棋盘。

          ArrayList<String> turns = new ArrayList<>();
          turns.add("Turn\t\tGuess\t\tBulls\t\tCows\n");
          turns.add("----------------------------------------------------");
          Scanner keyboard = new Scanner(System.in);
          String number = "1234";
          String guess = "";
          int attempts = 0;
      
          while(!number.equals(guess))
          {
              for(String line : turns)
                  System.out.println(line);
              System.out.println("Guess the magic number...");
              guess = keyboard.nextLine();
              attempts++;
              int bulls = checkBulls(guess, number);
              int cows = checkCows(guess, number);
              String attemptOutput = attempts + "\t\t" + guess + "\t\t" + bulls + "\t\t" + cows + "\n";
              turns.add(attemptOutput);
          }
      

      【讨论】:

        【解决方案4】:

        这是一个不同的实现,它从显示角度实现了相同的目标,但您应该注意,我正在通过多个新行清除屏幕,所以最终效果仍然相同,即...

        • 用户将在猜测列下输入数字
        • 每次尝试都会在用户按需要按 ENTER 后立即显示。

        注意:我有硬编码公牛和奶牛运行程序的价值。

        import java.util.ArrayList;
        import java.util.Scanner;
        
        public class Game {
        
            public static void main(String[] args) {
                ArrayList<String> attempts = new ArrayList<String>();
                attempts.add("Turn\t\tGuess\t\tBulls\t\tCows\n");
                attempts.add("----------------------------------------------------");
                Scanner keyboard = new Scanner(System.in);
                String number = "1234";
                String guess = "";
                int turn = 1;
        
                while (!number.equals(guess)) {
                    // multiple new lines to clear screen
                    System.out.println("\n\n\n\n\n\n\n\n");
                    for (String line : attempts)
                        System.out.println(line);
                    System.out.print(turn + "\t\t");
                    guess = keyboard.nextLine();
                    // checkbull implementation
                    int bulls = 0;
                    // checkcow implementation
                    int cows = 4;
                    String attemptOutput = turn + "\t\t" + guess + "\t\t" + bulls
                            + "\t\t" + cows;
                    turn++;
                    attempts.add(attemptOutput);
                }
            }
        }
        

        样品运行

        【讨论】:

          猜你喜欢
          • 2019-02-02
          • 2017-09-08
          • 2021-07-10
          • 2011-10-22
          • 2013-05-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多