Java 更新一行而不是整个屏幕

Java update one line instead of whole screen

我想知道如何在扫描 firstName 后更新 First_name,然后在扫描 lastName 后更新 Last_name。如果不重写整行,我不知道该怎么做。

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.print("First_name ");
        System.out.println("Last_name");

        System.out.println("Enter First name: ");
        String firstName = scan.nextLine();

        System.out.println("Enter Last name: ");
        String lastName = scan.nextLine();
    }
}

动态改变文本是不可能达到你想要的效果的。使用 System.out.println() 写入输出会将其写入控制台,之后,它就不受您的控制了。任何语言都是如此。

您可以在重新编写所有内容之前清除控制台,这会使它看起来更动态。这样做看起来像这样:

public static void clearScreen() {  
    System.out.print("3[H3[2J");  
    System.out.flush();  
}  

尽管它不能解决你原来的问题,但我确实想用这个post来指出马车的使用return然而:

System.out.print("This is a test-string!");
System.out.println("\rThis string will overwrite that string!");

回车return,在Java中用作\r,会将光标放回行首。这将覆盖原始字符串。此代码的输出将是:

This string will overwrite that string!