简体   繁体   English

如何在与用户输入的同一行中打印某些内容?

[英]How can I print something in the same line as the user input?

I wrote this code:我写了这段代码:

import java.util.Scanner;
public static void main (String[] args){
   Scanner scan = new Scanner (System.in);
   String inp;
   int m;
   System.out.println ("Please enter some characters.");
   inp = scan.nextLine();
   m = inp.length();
   System.out.println(" = " + m);
}

If I run that, I get something like this:如果我运行它,我会得到这样的东西:

Please enter some characters.
12345
 = 5

But how can I get the = 5 to be printed on the same line as the characters entered by the user, like below?但是,如何将= 5打印在与用户输入的字符相同的行上,如下所示?

Please enter some characters.
12345 = 5

There is no function in standard Java that allows you to easily do this.标准 Java 中没有任何函数可以让您轻松地做到这一点。

You will need to interact with the terminal using ANSI escape codes .您将需要使用ANSI 转义码与终端交互。 This is not supported by all terminals.并非所有终端都支持这一点。

You could also use a library that will do this for you, some examples in random order:您还可以使用一个可以为您执行此操作的库,一些示例以随机顺序排列:

just write like this:就这样写:

System.out.print(" = " + m);

println prints to a new line. println打印到一个新行。 hope it works希望它有效

 System.out.print("Please enter some characters.");
 inp = scan.nextLine();
 m = inp.length();
 System.out.println(" = " + m);

When you print the question, remove the ln part ( System.out.print("Please enter....) ) This will allow your input to be on the same line as the prompt. Then you can print System.out.println( inp + " = " + m); However you can't type something after the input as far as i know but you can echo it.打印问题时,删除 ln 部分( System.out.print("Please enter....) )这将允许您的输入与提示在同一行。然后您可以打印System.out.println( inp + " = " + m);然而,据我所知,你不能在输入后输入一些东西,但你可以回应它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM