简体   繁体   中英

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?

Please enter some characters.
12345 = 5

There is no function in standard Java that allows you to easily do this.

You will need to interact with the terminal using ANSI escape codes . 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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