Gon49
Gon49

Reputation: 17

How to display an output on the same line after taking an input

I'm working on java and I want to print a variable after taking an input (on the same line).
I have already tried backslash b ("\b") but it doesn't works.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
byte number = scanner.nextByte();
System.out.println("\b");
System.out.println(number);

The output is:

Enter a number: 23 //input

23 //output

I have also tried:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
byte number = scanner.nextByte();
System.out.println("\b" + number);

But it doesn't works either.

Upvotes: 0

Views: 1204

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

One can use java.io.Console

    Console con = System.console(); // null when there is no console like in the IDE.

    // Password without echo of entered char:
    char[] password = con.readPassword("Enter password: ");
    con.printf("Your password '%s' was correct.%n", new String(password));
    Arrays.set(password, ' '); // Normally done to not linger the password in memory.

    String answer = con.readLine("%nEnter a number between %d and %d: ", -128, 127);
    byte number = Byte.parseByte(answer);
    con.printf("Your number was %d, unsigned %d.%n", number, number & 0xFF);

Elaboration

  • readPassword and readLine come in two overloaded forms. A pure read, and here with a prompt written first. The prompt is in String.format form, so it is a template string with % place holders, and parameters.
  • printf is pure write; also with format. The format %n is needed here for a newline.

Password I gave for completeness: one unbeatable reason not to use Scanner on System.in. Note the correct usage: password as char[], not String. A String is immutable, can be shared. It will linger in memory till the garbage collector makes its round. Meanwhile a virus might check that memory. But as char array one might clear its content after processing. (Here I did nothing and accepted any "password.")

The only caveat of System.console() it might give null: when in the IDE, when not in the command window.

Upvotes: 1

Iceberg
Iceberg

Reputation: 3332

System.in needs an enter key to know when to finish the line, so console output will always start from a new line. You might need to resort to other library like jline to accomplish your goal.

Upvotes: 1

Related Questions