Java - How to print() output to previous line afte

2020-07-02 08:51发布

I'm kind of new to Java and I'm still trying to get the hang of it, so I apologize if this is a stupid question, but I was wondering how to print the output on the same line as the input. For example, I'm programming a simple game where the user tries to guess a 4-digit number (rather like Mastermind). I've got the mechanics all figured out, but I'm having a hard time displaying it on the console. In the beginning it might look something like: (a)

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

Then, the user would input their guess: (b)

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

And as soon as the user hits enter, the program should check their guess against the secret number and output the number of "bulls" (digits in their guess that match the secret number exactly) and "cows" (digits in their guess that are part of the number but in the wrong position), and then start a new line and again await user input. So if the secret number were, say, 4321... (c)

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

Trouble is, I can't for the life of me figure out how to get the output to display on the same line as the input. Here's a snippet of what I have so far (stripped-down because the full code is much uglier):

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));

Which gets me as far as (b), but then when I hit enter, this happens:

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

I know this isn't really essential to the game and is probably just me making things more complicated than necessary, but it's driving me nuts. I suppose what's happening is that when you hit enter after typing in your guess, the program starts a new line and then prints the bulls and cows. Is there any way to get around this?

标签: java
4条回答
干净又极端
2楼-- · 2020-07-02 09:04

Here is a different implementation that will achieve the same goal from display perspective but you should note that I am clearing screen by multiple new lines so the final effect is still same i.e. ...

  • user will enter number under Guess column
  • each attempt will be displayed immediately after user presses ENTER as you wanted.

NOTE: I have hard-coded bulls and cows value for running the program.

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);
        }
    }
}

Sample Run

enter image description here

查看更多
Rolldiameter
3楼-- · 2020-07-02 09:10

You should look into Ansi Escape Codes.

Something like:

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

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

will result in:

1234   {next col}

(where 1234, followed by {RETURN} was entered by the user; in an appropriately supporting console.

"\033[1A" moves the cursor up 1 row; and "\033[xC" moves the cursor x to the right (where above we calculate x as the length of their guess).

Another option that you have with this approach is to clear the console ("\033[2J") so that you can just completely re-draw the table (which is probably easier to maintain).

查看更多
Anthone
4楼-- · 2020-07-02 09:17

Your problem is clear the console or clear a line which depend on the console you are working on and is SO dependend!

See Java Clear Console or Java clear Line

Anyway this example clear the lines and it works on Unix bash shell. (Not in Eclipse console) It uses "\b" to clear a char ( backslash)

 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;
        }
    }

The problem in your case is that you need to clear also the new line since you read input and theere is no easy way to read input without new line. See How to read a single char from the console in Java (as the user types it)?

查看更多
疯言疯语
5楼-- · 2020-07-02 09:19

I know this isn't your implementation but it might suffice. What you can do is print the progress of the game after each input. Then you can see the progress of the game after each attempt and the board will be updated each time.

    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);
    }
查看更多
登录 后发表回答