2

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
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Jos
  • 41
  • 1
  • 4
  • 3
    If you mean on the command line, the answer is no. – Gumbo Sep 16 '15 at 15:35
  • As an explanation to Gumbo's comment, this wouldn't be possible on the command line (e.g. using a `Scanner` and `System.in`) because Java doesn't even see the input until the user hits `ENTER`, which forces the `= 7` to be on another line. – Justin Sep 16 '15 at 15:50
  • You could always remember the input, clean the console and print input + output together, couldn't you? – Vic Sep 16 '15 at 15:55
  • Similar: [User input on same line?](https://stackoverflow.com/q/28011420) – Bernhard Barker Nov 17 '17 at 13:44

3 Answers3

0

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:

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
emilianogc
  • 880
  • 4
  • 19
0

just write like this:

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

println prints to a new line. hope it works

Enea Dume
  • 3,014
  • 3
  • 21
  • 36
0
 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.

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29