1

I'm writing a command line program that makes use of println to display text in a very specific format. The problem I encounter is that every time I ask the user to enter something via Scanner.nextLine(), the console automatically echos their input in the console. Is there a way to disable the console from immediately displaying the user's entered text? In case it matters, I am running Linux.

Andrew Lalis
  • 894
  • 3
  • 15
  • 26

1 Answers1

2

You can use the Console class and readPassword() method that comes with Java since version 6. That method disable the echo, but only reads array of chars that you must convert to whatever you need:

Console console = System.console();
if (console == null) {
    System.out.println("Console not active!");
    System.exit(0);
}

System.out.print("Type something, please: ");
// This won't echo anything 
char[] userInput = console.readPassword();
Eduardo Yáñez Parareda
  • 9,126
  • 4
  • 37
  • 50
  • 1
    This is a hack (workaround), that doesn't answer the question. Although it does seem to solve the problem the person who asked the question is having. Therefore this isn't actually the answer to the question, but the answer to the problem. – Hypersoft Systems Dec 04 '17 at 23:48